编写程序,定义抽象基类Container,由此派生出2个派生类球体类Sphere,圆柱体类Cylinder,分别用虚函数分别计算表面积和体积。(不要更改主程序)
题目:
编写程序,定义抽象基类Container,由此派生出2个派生类球体类Sphere,圆柱体类Cylinder,分别用虚函数分别计算表面积和体积。(不要更改主程序)
int main () {Container *ptr; Sphere s (5 ) ;ptr=&s; cout<<"The area of sphere is " <<ptr->area ()<<endl; cout<<"The colume of sphere is " <<ptr->volume ()<<endl; Cylinder c (3 ,7 ) ;ptr=&c; cout<<"The area of cylinder is " <<ptr->area ()<<endl; cout<<"The colume of cylinder is " <<ptr->volume ()<<endl; return 0 ;}
参考:
#include <iostream> using namespace std;#define PI 3.14 class Container {protected : double radius; public : Container (double r = 0 ) :radius (r) { } virtual double area () = 0 ; virtual double volume () = 0 ; }; class Sphere :public Container{public : Sphere (double r) :Container (r) { } double area () ; double volume () ; }; double Sphere::area () { return 4 * PI * radius * radius; } double Sphere::volume () { return 4 * PI * radius * radius * radius / 3 ; } class Cylinder :public Container{private : double high; public : Cylinder (double r, double h) :Container (r), high (h) { } double area () ; double volume () ; }; double Cylinder::area () { return PI * radius * radius * 2 + 2 * PI * radius * high; } double Cylinder::volume () { return PI * radius * radius * high; } int main (void ) { Container* ptr; Sphere s (5 ) ; ptr = &s; cout << "The area of sphere is " << ptr->area () << endl; cout << "The volume of sphere is " << ptr->volume () << endl; Cylinder c (3 , 7 ) ; ptr = &c; cout << "The area of cylinder is " << ptr->area () << endl; cout << "The volume of cylinder is " << ptr->volume () << endl; return 0 ; }
图片版: