定义一个点类Point,定义一个三角形类Triangle,给两个类设计合适不带参数的构造函数,在主程序中,创建一个Triangle类的对象cyl并采用默认值初始化,通过调用成员函数area得到面积并输出。
时间: 2024-05-16 13:15:21 浏览: 123
西南科技大学Java程序设计与实践 实验三 类的继承与多态的应用
5星 · 资源好评率100%
下面是代码示例:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
private:
double x, y;
public:
Point() { x = 0.0; y = 0.0; }
Point(double xval, double yval) { x = xval; y = yval; }
double getX() { return x; }
double getY() { return y; }
};
class Triangle {
private:
Point p1, p2, p3;
public:
Triangle() {}
Triangle(Point p1val, Point p2val, Point p3val) {
p1 = p1val;
p2 = p2val;
p3 = p3val;
}
double area() {
double a = sqrt(pow(p2.getX() - p1.getX(), 2) + pow(p2.getY() - p1.getY(), 2));
double b = sqrt(pow(p3.getX() - p2.getX(), 2) + pow(p3.getY() - p2.getY(), 2));
double c = sqrt(pow(p1.getX() - p3.getX(), 2) + pow(p1.getY() - p3.getY(), 2));
double s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
};
int main() {
Point p1(0, 0);
Point p2(1, 0);
Point p3(0, 1);
Triangle tri(p1, p2, p3);
cout << "The area of the triangle is: " << tri.area() << endl;
return 0;
}
```
输出结果为:
```
The area of the triangle is: 0.5
```
阅读全文