C++作业6.14

本文通过C++实现了一个抽象基类container,并派生出cube、sphere和cylinder三个子类,每个子类都能计算出对应的表面积和体积。通过指针指向不同类型的对象并调用虚函数的方法,展示了多态性的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
using namespace std;
const double PI= 3.14;

class container{
public:
	container(double r1)
	{
		r = r1;
	};
	container(double r1,double h1 )
	{
		r = r1;
		h= h1;

	};
	virtual void surface_area() = 0;
	virtual void volume() = 0;
protected:
		double r;
        double h;
};
class cube:public container
{
public:
	cube(double a) :container(a)
	{}
	void surface_area()
	{
		cout << "该正方体的边长为:" << r << "表面积为:" << 6*r*r<<endl;
	}
	void volume()
	{
		cout << "该正方体的边长为:" << r << "体积为:" << r*r*r <<endl;
	}
};
class sphere :public container
{
public:
	sphere(double a) :container(a)
	{}
	void surface_area()
	{
		cout << "该球体的半径为:" << r << "表面积为:" << 4*PI*r*r << endl;
	}
	void volume()
	{
		cout <<  "该球体的半径为:"  << r<< "体积为:" <<4/3*PI*r*r*r << endl;
	}
};
class cylinder :public container
{
public:
	cylinder(double a,double b) :container(a,b)
	{};
	void surface_area()
	{
		cout << "该圆柱体的半径为:" << r << "高为:" << h << "表面积为:" << PI*r*r+2*PI*r*h<<endl;
	}
	void volume()
	{
		cout << "该圆柱体的半径为:" << r << "高为:" << h << "体积为:" << PI*r*r*h<< endl;
	}

};

int main()
{
	container *p;
	cube i(6.0);
	p = &i;
	p->surface_area();
	p->volume();
	sphere j(5.0);
	p = &j;
	p->surface_area();
	p->volume();
	cylinder k(5.0,6.5);
	p = &k;
	p->surface_area();
	p->volume();
	return 0;
}
<img src="https://img-blog.youkuaiyun.com/20150516184326716?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvU2FrdXJhcmFpbjc3/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值