C++由圆派生球,圆柱,圆锥

C++由圆派生球,圆柱,圆锥

思路

设计的一个基类Circle类,再分别派生出圆球类Ball,圆锥类Taper 圆柱类Cylinder使用相关编程题方法求出圆的面积,其他几何图形的表面积和体积

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <cmath>
using namespace std;
const long double PI = 3.1415926;
class Circle
{
public:
virtual long double area() = 0;//获得表面积
virtual long double volume() = 0;//获得体积
};
//球
class Ball:public Circle
{
public:
Ball(long double radius):m_radius(radius){}
long double volume(){
return 4.0/3.0 * PI * m_radius * m_radius * m_radius;
}
long double area(){
return 4 * PI * m_radius * m_radius;
}
private:
long double m_radius; //球的半径
};
//圆柱
class Cylinder:public Circle{
public:
Cylinder(long double radius, long double high):m_radius(radius),m_high(high){}
long double volume(){
return PI * m_radius * m_radius * m_high;
}
long double area(){
return PI * m_radius * m_radius + 2.0 * PI * m_radius * m_high;
}
private:
long double m_radius; //圆柱的半径
long double m_high; //圆柱的高
};
//圆锥
class Taper :public Circle
{
public:
Taper (long double radius, long double high):m_radius(radius),m_high(high){
this->m_coneElement = sqrt(m_high * m_high + m_radius * m_radius);
}
long double volume(){
return 1.0/3.0 * PI * m_radius * m_radius * m_high;
}
long double area(){
return PI * m_radius * (m_radius + m_coneElement);
}
private:
long double m_radius;//圆锥的半径
long double m_high; //圆锥的高
long double m_coneElement; //圆锥的母线长

};

int main()
{
Circle *p = NULL;
p = new Taper (3,4);
cout << "圆锥(3,4)的表面积是:" << p->area() << " 体积是:" << p->volume() << endl;
delete p;
p = NULL;
//
p = new Cylinder(6,4);
cout << "圆柱(6,4)的表面积是:" << p->area() << " 体积是:" << p->volume() << endl;
delete p;
p = NULL;
//
p = new Ball(6);
cout << "球(6)的表面积是:" << p->area() << " 体积是:" << p->volume() << endl;
delete p;
p = NULL;
//
return 0;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!