设计一个名为Triangle的类,扩展了GeometricObject。类包含以下内容: 命名为sidel, side2和side3的三个双数据字段表示三角形的三条边。 一个无参数构造函数,它创建一个默认三角形,每条边为1.0。一个构造函数,用于创建具有指定的sidel、side2和side3的三角形。 常量访问器用于所有三个数据字段。 一个名为getArea()的常量函数,它返回三角形的面积。一个名为getPerimeter()的常量函数,它返回三角形的周长。绘制涉及类三角形和几何对象的UML图。实现类。编写一个测试程序,提示用户输入三角形的三条边,输入颜色,并输入1或0以指示三角形是否填充。程序应创建具有这些边的三角形对象,并使用输入设置颜色和填充属性。程序应显示面积、周长、颜色和true或false,以指示是否填充。利用c++编译
时间: 2024-02-03 10:14:03 浏览: 62
以下是Triangle类的头文件:
```cpp
#ifndef TRIANGLE_H
#define TRIANGLE_H
#include "GeometricObject.h"
class Triangle : public GeometricObject {
public:
Triangle();
Triangle(double side1, double side2, double side3);
double getSide1() const;
double getSide2() const;
double getSide3() const;
double getArea() const;
double getPerimeter() const;
private:
double side1, side2, side3;
};
#endif
```
以下是Triangle类的实现文件:
```cpp
#include "Triangle.h"
#include <cmath>
Triangle::Triangle() {
side1 = side2 = side3 = 1.0;
}
Triangle::Triangle(double side1, double side2, double side3) {
this->side1 = side1;
this->side2 = side2;
this->side3 = side3;
}
double Triangle::getSide1() const {
return side1;
}
double Triangle::getSide2() const {
return side2;
}
double Triangle::getSide3() const {
return side3;
}
double Triangle::getArea() const {
double s = getPerimeter() / 2;
return std::sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
double Triangle::getPerimeter() const {
return side1 + side2 + side3;
}
```
测试程序:
```cpp
#include <iostream>
#include "Triangle.h"
using namespace std;
int main() {
double side1, side2, side3;
string color;
int filled;
cout << "Enter three sides of the triangle: ";
cin >> side1 >> side2 >> side3;
cout << "Enter the color of the triangle: ";
cin >> color;
cout << "Enter 1 for filled, 0 for not filled: ";
cin >> filled;
Triangle t(side1, side2, side3);
t.setColor(color);
t.setFilled(filled == 1);
cout << "Area of the triangle is " << t.getArea() << endl;
cout << "Perimeter of the triangle is " << t.getPerimeter() << endl;
cout << "Color of the triangle is " << t.getColor() << endl;
cout << "Is the triangle filled? " << (t.isFilled() ? "true" : "false") << endl;
return 0;
}
```
UML图:
```
+--------------------------+
| GeometricObject |
|--------------------------|
| -color: string |
| -filled: bool |
|--------------------------|
| +GeometricObject() |
| +GeometricObject(color: string, filled: bool) |
| +getColor(): string |
| +setColor(color: string): void |
| +isFilled(): bool |
| +setFilled(filled: bool): void |
+--------------------------+
^
|
|
+--------------------------+
| Triangle |
|--------------------------|
| -side1: double |
| -side2: double |
| -side3: double |
|--------------------------|
| +Triangle() |
| +Triangle(side1: double, side2: double, side3: double) |
| +getSide1(): double |
| +getSide2(): double |
| +getSide3(): double |
| +getArea(): double |
| +getPerimeter(): double |
+--------------------------+
```
阅读全文