用输出显示析构顺序
时间: 2023-12-07 08:05:01 浏览: 74
好的,请看以下代码实现:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
double x, y;
Point(double _x = 0, double _y = 0) : x(_x), y(_y) {
cout << "构造函数被调用" << endl;
}
~Point() {
cout << "析构函数被调用" << endl;
}
};
double distance(Point a, Point b) {
double dx = a.x - b.x, dy = a.y - b.y;
return sqrt(dx * dx + dy * dy);
}
int main() {
int n;
cout << "请输入点的个数n:";
cin >> n;
Point* points = new Point[n];
cout << "请输入" << n << "个点的坐标:" << endl;
for (int i = 0; i < n; i++) {
cin >> points[i].x >> points[i].y;
}
cout << "这" << n << "个点的坐标为:" << endl;
for (int i = 0; i < n; i++) {
cout << "(" << points[i].x << ", " << points[i].y << ")" << endl;
}
double len = 0;
for (int i = 1; i < n; i++) {
len += distance(points[i-1], points[i]);
}
cout << "这" << n << "个点组成的折线长度为:" << len << endl;
delete[] points;
cout << "内存空间已被释放" << endl;
return 0;
}
```
在这个代码中,我们在 Point 类中添加了一个析构函数,用来输出析构函数被调用的信息。在 main 函数中,我们在 delete 语句后面添加了一行输出语句,用来表示内存空间已被释放。这样,当程序运行时,我们就可以看到析构函数的调用顺序了。
阅读全文