Figure 类有一个数据成员radius和虚函数area ()和volume()。从Figure类派生出Sphere类和Column类,分别实现求球体和圆柱体的体积和表面积。并编写测试程序。
#include<iostream>
#include<cmath>
using namespace std;
const double pi = 3.14;
class Figure
{
public:
Figure(){};
Figure(double r){radius = r;};
virtual double area(){return 0.0;}
virtual double volume(){return 0.0;}
~Figure(){};
protected:
double radius;
};
class Sphere:public Figure
{
public:
Sphere(double r){radius = r;}
virtual double area(){return 4 * pi * pow(radius, 2);}
virtual double volume(){return 4/3.0 * pi * pow(radius, 3); }
~Sphere(){};
};
class Column:public Figure
{
public:
Column(){};
Column(double r, int h){radius = r;H = h;}
virtual double area(){return pi * pow(radius, 2) * H;}
virtual double volume(){return 2 * pi * pow(radius, 2) + 2 * pi * radius * H;}
~Column(){};
private:
int H;
};
void func(Figure &p)
{
cout << "area = " << p.area() << endl;
cout << "volume = " << p.volume() << endl;
}
int main()
{
int r = 3;
int h = 4;
Figure F(r);
Sphere S(r);
cout << "Sphere:\n";
func(S);
Column C(r, h);
cout << "Column:\n";
func(C);
return 0;
}
p.area() 对象加访问函数,可以直接输出成员函数返回值
基类的数据成员可以继承,但需要再次赋值,Sphere S(r)-虽然先构造基类的构造函数,但是不会赋值给基类的数据成员