示例代码:
#include
#include
using namespace std;
const double PI=3.14;
class Shape//抽象类
{
public:
virtual void Area()=0;//纯虚函数
};
class Rectangle:public Shape //继承方式必须为public
{
public:
Rectangle(int a1,int b1) {a=a1; b=b1;}
virtual void Area()
{
s=(a*b)/2.0;
cout<<"三角形面积为:"<}
private:
int a,b;
double s;
};
class Square:public Shape//矩形类
{
public:
Square(float a1, float b1) {a = a1, b = b1;}
virtual void Area()
{
s=a*b;
cout<<"矩形面积为:"<}
private:
float a, b;
double s;
};
class Circle:public Shape//圆类
{
public:
Circle(float myr) {r=myr;}
virtual void Area()
{
s=r*r*PI;
cout<<"圆的面积为:"<}
private:
float r;
double s;
};
void Show(Shape *p)//基类指针p
{
p->Area();
}
int main() {
double a, b;
cin>>a>>b;
Shape *p;//抽象类不能实例化但是可以定义指针或是引用
Rectangle Re(a, b);
p=ℜ//派生类对象地址赋给基类指针
Show(p);
Square Sq(a, b);
p=&Sq;
Show(p);
Circle C(a);
p=&C;
Show(p);
}