设计一个抽象类Shape。在此基础上派生出类Triangle和Circle,两者都有计算对象面积的函数GetArea和计算对象周长的函数GetPerim。编写程序测试。
时间: 2023-11-22 16:55:49 浏览: 56
采用面向对象的程序设计方法编写一个计算图形面积的类,程序应当能够计算并输出圆、矩形和三角形的面积。
5星 · 资源好评率100%
以下是实现代码:
```cpp
#include <iostream>
using namespace std;
class Shape {
public:
virtual double GetArea() = 0;
virtual double GetPerim() = 0;
};
class Triangle : public Shape {
private:
double a, b, c;
public:
Triangle(double _a, double _b, double _c) : a(_a), b(_b), c(_c) {}
double GetArea() {
double s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
double GetPerim() {
return a + b + c;
}
};
class Circle : public Shape {
private:
double r;
public:
Circle(double _r) : r(_r) {}
double GetArea() {
return 3.1415926 * r * r;
}
double GetPerim() {
return 2 * 3.1415926 * r;
}
};
int main() {
Shape* p[2];
p[0] = new Triangle(3, 4, 5);
p[1] = new Circle(2);
for (int i = 0; i < 2; ++i) {
cout << "Area: " << p[i]->GetArea() << endl;
cout << "Perim: " << p[i]->GetPerim() << endl;
}
return 0;
}
```
输出结果为:
```
Area: 6
Perim: 12
Area: 12.5664
Perim: 12.5664
```
阅读全文