标签:15 2021.05 double area volume Sphere radius 圆柱体 Container
原文链接:
- 自动车
- 手动车: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;
}
图片版:
标签:15,2021.05,double,area,volume,Sphere,radius,圆柱体,Container 来源: https://blog.csdn.net/MailWithoutName/article/details/116846816
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。