声明一个Shape基类,在此基础上公有派生出矩形Rectangle类和圆Circle类,二者都有函数GetArea()计算对象的面积,利用矩形类公有派生一个正方形Square类。具体要求如下:
(1)Shape基类的公有成员为:
Shape():构造函数
float GetArea():
void Print():
(2)Rectangle类的公有成员为:
Rectangle(float l, float w):构造函数
GetArea():计算矩形的面积
Print(): 输出矩形的长、宽和面积
私有成员为:
float width:矩形的宽
float length:矩形的长
(3)Circle类的公有成员为:
Circle(float r):构造函数
GetArea():计算圆的面积
Print():输出圆的半径和面积
私有成员为:
float radius:圆的半径
(4)Square类的公有成员为:
Square(float l):构造函数
(5)主函数中通过Shape指针sp来实现对其他派生类对象的操作。
//导入头文件 #include3.运行结果using namespace std; class Shape{ public: //无参构造函数 Shape(){ } virtual float GetArea(){ //定义为虚函数 return -1; } virtual void Print(){ } //定义为虚函数 }; class Rectangle:public Shape{ public: //无参构造 Rectangle(){ } //有参构造 Rectangle(float l,float w){ width=w; length=l; } //计算矩阵面积 virtual float GetArea(){ //定义为虚函数 return (width*length); } //输出 virtual void Print(){ //定义为虚函数 cout<<"Length:"< Print(); //输出 sp=&rectangle;//sp指向Rectangle sp->Print(); //输出 return 0; }



