2021.05.15继承球体和圆柱体

原文链接:

  • 自动车
  • 手动车:https://codeeggs.github.io/2021/05/15/2021.05.15%E7%BB%A7%E6%89%BF%E7%90%83%E4%BD%93%E5%92%8C%E5%9C%86%E6%9F%B1%E4%BD%93/
    题目:

编写程序,定义抽象基类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;

}

图片版:
2021.05.15继承球体和圆柱体

上一篇:你知道思科WLC的RADIUS认证服务器被标记为*是什么意思吗?


下一篇:java设计程序的第 3 次实验