[C++]纯虚函数

任何包含一个或者多个的纯虚函数都叫做抽象类,因此不能对它实例化.否则会导致编译错误;

从抽象类继承而来的类若不覆盖纯虚函数,依然是纯虚函数,所以派生类务必覆盖纯虚函数

纯虚函数定义

可以到我这一篇源代码

#include <iostream>
using namespace std;
#define PI 3.1415926
class Shape
{
public:
virtual void Print()=0;
virtual float Area()=0;

};
class Circle: public Shape
{
float R;
public:
Circle(float R);
void Print();
float Area();
};

Circle::Circle(float R)
{
this->R=R;
}

void Circle::Print()
{
cout<<"the R of this Circle is "<<R<<endl;
}

float Circle::Area()
{
return PI*R*R;
}



class Rectangle:public Shape
{
float length,width;
public:
Rectangle(float length,float width);
void Print();
float Area();
};

Rectangle::Rectangle(float length,float width)
{
this->length=length;
this->width=width;
}
void Rectangle::Print()
{
cout<<"the length is "<<length<<endl<<"the width is "<<width<<endl;
}
float Rectangle::Area()
{
return length*width;

}
int main()
{
Shape *S;
S = new Circle(10);
S->Print();
cout<<"the Area of the Circle is "<<S->Area()<<endl;
delete S;
S = new Rectangle(10,5);
S->Print();
cout<<"the Area of the Rectangle is "<<S->Area()<<endl;
int n;
cin>>n;
return 0;
}
作者: 林羽飞扬
出处:http://www.cnblogs.com/zhengyuhong/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留作者信息,且在文章页面明显位置给出原文连接



你可能感兴趣的:(C++)