建立一个Point(点)类,包含虚函数(virtual double area() {return 0})。以它为基类,派生出一个Circle(圆)类,增加数据成员r(半径)、构造函数及求圆面积的函数area(),再以Circle类为直接基类,派生出一个Cylinder(圆柱体)类,再增加数据成员h(高)、构造函数及求圆柱表面积的函数area()。要求编写程序,定义Circle类及Cylinder类的对象(对象数据定义时给出),利用指向基类的指针,分别输出圆的面积和圆柱体的表面积。
1条回答 默认 最新
- 暖晴的天 2021-06-20 02:58关注
答案如下:
class Point { public: Point() {} ~Point() {} virtual double area() { return 0; } }; class Circle:public Point { public: Circle(double R) { r = R; } ~Circle() {} double area() { return 3.14*r*r; } public: double r; }; class Cylinder :public Point { public: Cylinder(double R, double H) { r = R; h = H; } ~Cylinder() {} double area() { return 2 * 3.14 * r *( r + h ); } public: double r; double h; }; int main() { Circle *cl = new Circle(5); Cylinder *cyl = new Cylinder(5, 10); Point* p = cl; std::cout << "圆的面积为:" << p->area() << std::endl; p = cyl; std::cout << "圆柱体的表面积:" << p->area() << std::endl; if (cl != NULL) delete cl; if (cyl != NULL) delete cyl; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报