具体代码如下
#include
#include
using namespace std;
class Point { //坐标点类
public:
const double x, y;
Point(double x = 0.0, double y = 0.0) : x(x), y(y) {}
double distanceTo(Point p)const { //到指定点的距离
return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y));
}
};
class Line { //线段类
public:
const Point p1, p2;//两个端点
Line(Point p1, Point p2) :p1(p1), p2(p2) {}
double length()
{
//两点间距离
/******begin********/
return p1.distanceTo(p2);
/********end*********/
}
};
//请在此处按题目要求编写代码
class Triangle {//三角形2
public:
/***********begin*********************/
Point* p1;
Point* p2;
Point* p3;
Triangle(Point p1, Point p2, Point p3) {
this->p1 = &p1;
this->p2 = &p2;
this->p3 = &p3;
}
double length1() {
Line l1(*p1, *p2);
return l1.length();
}
double length2() {
Line l2(*p3, *p2);
return l2.length();
}
double length3() {
Line l3(*p1, *p3);
return l3.length();
}
double area() {
double s, a, b, c;
a = length1();
b = length2();
c = length3();
s = (a + b + c) / 2;
return sqrt(s * (s - a) * (s - b) * (s - c));
}
/***********end***********************/
};
//请不要修改 main 函数
int main() {
Triangle r(Point(0.0, 8.0), Point(5.0, 0.0), Point(0.0, 0.0));
cout << "Side 1: " << r.length1() << endl;
cout << "Side 2: " << r.length2() << endl;
cout << "Side 3: " << r.length3() << endl;
cout << "area: " << r.area() << endl;
return 0;
}
用调试在clion运行lenth1时候指针的值突然变化,十分离谱
是不是,不能把地址作为属性啊,不同IDE对于这个地址指向回收也不同导致运行到一半,地址指的值被回收了。。。