一、题目描述
class Point
{
double x, y;
public:
Point();
Point(double x_value, double y_value); // 缺省构造函数,给 x, y 分别赋值为0
~Point(); // 析构函数
double getX(); // 返回x的值
double getY(); // 返回y的值
void setXY(double x1, double y1){x = x1; y = y1;}
void setX(double x_value); // 设置x的值
void setY(double y_value); // 设置y的值
double getDisTo(Point &p); // 计算当前点到参数点p的距离
};
上面是我们曾经练习过的一个习题,请在原来代码的基础上作以下修改:
1.增加自写的拷贝构造函数;
2.增加自写的析构函数;
3.将getDisTo方法的参数修改为getDisTo(const Point &p);
4.根据下面输出的内容修改相应的构造函数。
然后在主函数中根据用户输入的数目建立Point数组,求出数组内距离最大的两个点之间的距离值。
二、输入与输出
1.输入
测试数据的组数 t
第一组点的个数
第一个点的 x 坐标 y坐标
第二个点的 x坐标 y坐标
…
2
4
0 0
5 0
5 5
2 10
3
-1 -8
0 9
5 0
2.输出
Constructor.
Constructor.
Constructor.
Constructor.
The longeset distance is 10.44,between p[1] and p[3].
Distructor.
Distructor.
Distructor.
Distructor.
Constructor.
Constructor.
Constructor.
The longeset distance is 17.03,between p[0] and p[1].
Distructor.
Distructor.
Distructor.
三、参考代码
#include <iostream>
#include<iomanip>
#include<cmath>
#include<algorithm>
using namespace std;
class Point
{
double x, y;
public:
Point() { x = 0; y = 0; cout << "Constructor." << endl; };
Point(double x_value, double y_value) {
x = x_value; y = y_value; cout << "Constructor." << endl;
}; // 缺省构造函数,给 x, y 分别赋值为0
~Point() { cout << "Distructor." << endl; }; // 析构函数
double getX() { return x; }; // 返回x的值
double getY() { return y; }; // 返回y的值
void setXY(double x1, double y1) { x = x1; y = y1; }
void setX(double x_value) { x = x_value; }; // 设置x的值
void setY(double y_value) { y = y_value; }; // 设置y的值
double getDisTo(Point& p) { return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y)); }; // 计算当前点到参数点p的距离
};
int main()
{
int sum;
cin >> sum;
int num;
double x, y;
while (sum--) {
cin >> num;
Point* p = new Point[num];
for (int i = 0; i < num; i++) {
cin >> x >> y;
p[i].setXY(x, y);
}
int maxi = 0;
int maxj = 0;
double maxdis = 0;
for (int i = 0; i < num; i++) {
for (int j = i + 1; j < num; j++) {
if (p[i].getDisTo(p[j]) > maxdis) {
maxdis = p[i].getDisTo(p[j]);
maxi = i;
maxj = j;
}
}
}
cout << "The longeset distance is " << fixed << setprecision(2) << maxdis;
cout << ",between p[" << maxi << "] and p[" << maxj << "]." << endl;
delete[]p;
}
}