其他分享
首页 > 其他分享> > 2021.05.15继承球体和圆柱体

2021.05.15继承球体和圆柱体

作者:互联网

原文链接:

编写程序,定义抽象基类Container,由此派生出2个派生类球体类Sphere,圆柱体类Cylinder,分别用虚函数分别计算表面积和体积。(不要更改主程序)

int main()
{
Container *ptr;
Sphere s(5);
ptr=&s;
cout<<"The area of sphere is "<<ptr->area()<<endl;
cout<<"The colume of sphere is "<<ptr->volume()<<endl;
Cylinder c(3,7);
ptr=&c;
cout<<"The area of cylinder is "<<ptr->area()<<endl;
cout<<"The colume of cylinder is "<<ptr->volume()<<endl;
return 0;
}

参考:

#include <iostream>
using namespace std;
#define PI 3.14
class Container {
protected:
	double radius;
public:
	Container(double r = 0) :radius(r) {	}
	virtual double area();
	virtual double volume();
};
double Container::area() {
	return 0;
}
double Container::volume() {
	return 0;
}
class Sphere :public Container{
public:
	Sphere(double r) :Container(r) {	}
	double area();
	double volume();
};
double Sphere::area() {
	return 4 * PI * radius * radius;
}
double Sphere::volume() {
	return 4 * PI * radius * radius * radius / 3;
}
class Cylinder :public Container{
private:
	double high;
public:
	Cylinder(double r, double h) :Container(r), high(h) {	}
	double area();
	double volume();
};
double Cylinder::area() {
	return PI * radius * radius * 2 + 2 * PI * radius * high;
}
double Cylinder::volume() {
	return PI * radius * radius * high;
}
int main(void) {
	Container* ptr;
	Sphere s(5);
	ptr = &s;
	cout << "The area of sphere is " << ptr->area() << endl;
	cout << "The volume of sphere is " << ptr->volume() << endl;
	Cylinder c(3, 7);
	ptr = &c;
	cout << "The area of cylinder is " << ptr->area() << endl;
	cout << "The volume of cylinder is " << ptr->volume() << endl;
	return 0;

}

图片版:
在这里插入图片描述

标签:15,2021.05,double,area,volume,Sphere,radius,圆柱体,Container
来源: https://blog.csdn.net/MailWithoutName/article/details/116846816