1.使用c++, 在 point.h 头文件中定义 Point 类,数据成员为一个点的 x 坐标、y 坐标,自定义 合适的构造函数,根据需要定义其他成员函数(可以定义成员函数计算当前 Point 类对 象到另一个 Point 类对象的距离)。在 triangle.h 头文件中定义 Triangle 类,数据成员为 三个 Point 类对象(分别对应于三角形的三个顶点),定义成员函数分别实现计算周长、 计算面积,定义重载运算符函数 operator>比较两个三角形的面积,自定义六参数构造函 数(参数分别对应 3 个顶点的 x 坐标、y 坐标)和复制构造函数,根据需要定义其他成 员函数。 要求: (1) 在 main 函数中创建 triangle 类对象 t1,三个顶点坐标分别为(1,1)、(3,4)、 (2,5),调用成员函数输出三角形的周长和面积。 (2) 调用复制构造函数创建 triangle 类对象 t2(复制于 t1),调用重载运算符函 数 operator>判断 t1 的面积是否大于 t2。
时间: 2023-05-21 16:06:41 浏览: 165
以下是 Point 类和 Triangle 类的代码实现:
point.h:
```
#include <cmath>
class Point {
public:
Point(double x, double y) : x_(x), y_(y) {}
double get_x() { return x_; }
double get_y() { return y_; }
double distance_to(const Point& other) {
double dx = x_ - other.x_;
double dy = y_ - other.y_;
return sqrt(dx*dx + dy*dy);
}
private:
double x_;
double y_;
};
```
triangle.h:
```
#include "point.h"
class Triangle {
public:
Triangle(double x1, double y1, double x2, double y2, double x3, double y3):
p1_(x1, y1), p2_(x2, y2), p3_(x3, y3) {}
Triangle(const Point& p1, const Point& p2, const Point& p3):
p1_(p1), p2_(p2), p3_(p3) {}
double perimeter() {
double d1 = p1_.distance_to(p2_);
double d2 = p2_.distance_to(p3_);
double d3 = p3_.distance_to(p1_);
return d1 + d2 + d3;
}
double area() {
double a = p1_.distance_to(p2_);
double b = p2_.distance_to(p3_);
double c = p3_.distance_to(p1_);
double s = (a + b + c) / 2.0;
return sqrt(s*(s-a)*(s-b)*(s-c));
}
bool operator>(const Triangle& other) {
return area() > other.area();
}
private:
Point p1_;
Point p2_;
Point p3_;
};
```
在 main 函数中,我们可以这样使用:
```
#include <iostream>
#include "triangle.h"
int main() {
Triangle t1(1, 1, 3, 4, 2, 5);
std::cout << "Perimeter of t1: " << t1.perimeter() << std::endl;
std::cout << "Area of t1: " << t1.area() << std::endl;
Triangle t2 = t1;
std::cout << "Is area of t1 greater than t2? " << (t1 > t2) << std::endl;
return 0;
}
```
输出结果为:
```
Perimeter of t1: 8.47214
Area of t1: 3.5
Is area of t1 greater than t2? 0
```
注意,以上代码是使用 C++ 编写的,若要使用 C 语言编写,需要做出相应修改。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)