2021-11-08

编写计算正方体、圆柱体、球体的表面积和体积的类。要去:
(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;

}

在这里插入图片描述
可以选择虚拟继承,或者不选择虚拟继承,但选择虚拟继承可以有效的避免二义性的问题!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值