编写计算正方体、圆柱体、球体的表面积和体积的类。要去:
(1) 这三个类有一个公共的基类;(2) 这三个类计算正方体、圆柱体、球体的表面积和体积的成员函数名字相同;(3) 按照运行时的多态性方法设计一个测试主函数,并进行测试。
#include<iostream>
using namespace std;
class body {
protected:
float length;
float width;
float height;
double v;
double s;
public:
virtual void get_message();
virtual void get_s() = 0;
virtual void get_v() = 0;
void show_message();
};
class cuboid :virtual public body {
public:
cuboid() {};
void get_message();
void get_s();
void get_v();
~cuboid() {};
};
class cylinder :virtual public body {
protected:
float r;
public:
cylinder() {};
void get_message();
void get_s();
void get_v();
~cylinder() {};
};
class sphere :public body {
protected:
float r;
public:
sphere() {};
void get_message();
void get_s();
void get_v();
~sphere() {};
};
void body::get_message() {}
void body::show_message() {
cout << "S" << s << endl;
cout << "V" << v << endl;
}
void cuboid::get_message() {
cout << endl << "请输入长:";
cin >> length;
cout << endl << "请输入宽:";
cin >> width;
cout << endl << "请输入高:";
cin >> height;
cout << endl;
}
void cuboid::get_s() {
s = 2 * length * width + 2 * length * height + 2 * width * height;
}
void cuboid::get_v() {
v = length * width * height;
}
void cylinder::get_message() {
cout << endl << "请输入半径:";
cin >> r;
cout << endl << "请输入高:";
cin >> height;
cout << endl;
}
void cylinder::get_s() {
s = 2 * 3.14 * r * r + 2 * 3.14 * r * height;
}
void cylinder::get_v() {
v = 3.14 * r * r * height;
}
void sphere::get_message() {
cout << endl << "请输入半径:";
cin >> r;
cout << endl;
}
void sphere::get_s() {
s = 4 * 3.14 * r * r;
}
void sphere::get_v() {
v = (3.14 * r * r * r * 3) / 4;
}
int main() {
char TF;
int x;
body* a[3];
a[0] = new cuboid;
a[1] = new cylinder;
a[2] = new sphere;
while (1) {
cout << "请选择要计算的物体:" << endl;
cout << "0:长方体" << endl;
cout << "1:圆柱体" << endl;
cout << "2:球体" << endl;
cout << "请输入:";
cin >> x;
cout << endl;
a[x]->get_message();
a[x]->get_s();
a[x]->get_v();
a[x]->show_message();
cout << "是否继续(T/F)";
cin >> TF;
if (TF != 't' && TF != 'T')
break;
}
return 0;
}
可以选择虚拟继承,或者不选择虚拟继承,但选择虚拟继承可以有效的避免二义性的问题!