输出
The area of the Circle is 78.5 The area of the Rectagle is 30 The area of the Square is 64
class Shape{
public:
virtual float getArea()=0;
virtual ~Shape(){}
};
//你的代码将被嵌在这里
#include<iostream>
using namespace std;
class Circle :public Shape
{
float R;
public:
Circle(float n)
{
R = n;
}
float getArea()
{
return R * R * 3.14;
}
~Circle() {}
};
class Rectangle
{
float wide, lenth;
public:
Rectangle(float a, float b)
{
wide = a;
lenth = b;
}
float getArea()
{
return wide * lenth;
}
virtual ~Rectangle()
{}
};
class Square :public Rectangle
{
int c;
public:
Square(float a) :Rectangle(a, a)
{
c = a;
}
~Square() {}
};
int main()
{ Shape *ps;
ps=new Circle(5);
cout<<"The area of the Circle is "<<ps->getArea()<<endl;
delete ps;
Rectangle *pr;
pr=new Rectangle(5,6);
cout<<"The area of the Rectagle is "<<pr->getArea()<<endl;
delete pr;
Square s(8);
pr=&s;
cout<<"The area of the Square is "<<pr->getArea()<<endl;
delete pr;
return 0;
}
delete中pr只能用虚继承来继承Rectangle 因为构造是先构造父类析构是先析构子类如果直接delete自动调用的析构Square就没了