定义一个 Shape 基类,在此基础上派生出 Rectangle 和 Circle,二者都有 GetArea()函数计算对象的面积。使用 Rectangle 类创建一个派生类 Square。
解:
源程序:
#include <iostream.h> class Shape { public: Shape(){} ~Shape(){} virtual float GetArea() { return -1; } }; class Circle : public Shape { public: Circle(float radius):itsRadius(radius){} ~Circle(){} float GetArea() { return 3.14 * itsRadius * itsRadius; } private: float itsRadius; }; class Rectangle : public Shape { public: Rectangle(float len, float width): itsLength(len), itsWidth(width){}; ~Rectangle(){}; virtual float GetArea() { return itsLength * itsWidth; } virtual float GetLength() { return itsLength; } virtual float GetWidth() { return itsWidth; } private: float itsWidth; float itsLength; }; class Square : public Rectangle { public: Square(float len); ~Square(){} }; Square::Square(float len); Rectangle(len,len) { } void main() { Shape * sp; sp = new Circle(5); cout << "The area of the Circle is " << sp->GetArea () << endl; delete sp; sp = new Rectangle(4,6); cout << "The area of the Rectangle is " << sp->GetArea() << endl; delete sp; sp = new Square(5); cout << "The area of the Square is " << sp->GetArea() << endl; delete sp; }
程序运行输出:
The area of the Circle is 78.5
The area of the Rectangle is 24
The area of the Square is 25
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题
解:
源程序:
程序运行输出:
The area of the Circle is 78.5
The area of the Rectangle is 24
The area of the Square is 25