12月测试题:5.圆柱类设计与测试
设计一个圆柱类(其父类是圆类),设计成员函数输出它们的面积。
圆周率用3.1415926参与计算。
后置代码:
int main()
{
double a,b;
cin>>a>>b;
Column column(a,b);
cout<<"面积:"<<column.getArea()<< endl;
Circle &c=column;
cout<<"面积:"<<c.getArea()<< endl;
return 0;
}
分析:难度不大的继承问题
题解:
#include <iostream>
using namespace std;
double pi=3.1415926;
class Circle
{
public:
double r;
Circle(double a)
{
r=a;
cout<<"圆类构造函数被调用"<<endl;
}
double getArea()
{
return pi*r*r;
}
} ;
class Column:public Circle
{
public:
double h;
Column(double a,double b):Circle(a)
{
h=b;
cout<<"圆柱类构造函数被调用"<<endl;
}
double getArea()
{
return pi*r*r*2+2*pi*r*h;
}
};
int main()
{
double a,b;
cin>>a>>b;
Column column(a,b);
cout<<"面积:"<<column.getArea()<< endl;
Circle &c=column;
cout<<"面积:"<<c.getArea()<< endl;
return 0;
}