#include<iostream>
using namespace std;
class Coordinate
{
public:
Coordinate()
{
times = 2;
cout << "Coordinate construction1 called!" << endl;// 设置默认的输入坐标数目
}
Coordinate(int times1)
{
times = times1;
cout << "Coordinate construction2 called!" << endl; // 设置输入坐标数目
}
~Coordinate()
{
cout << "Coordinate destruction called!" << endl;// 析构函数
}
void InputCoord()
{
for (int i = 0; i < times; i++)
{
cout << "Please Input x:" << endl;
cin >> Coord[i][1];
cout << "Please Input y:" << endl;
cin >> Coord[i][2];
}// 输入坐标
}
void ShowCoord()
{
cout << "The coord is:" << endl;
for (int i = 0; i < times; i++)
{
cout << "(" << Coord[i][1] << "," << Coord[i][2] << ")" << endl;
}// 显示已经输入的坐标
}
void ShowAvgCoord()
{
float avgx = 0;
float avgy = 0;
for (int i = 0; i < times; i++)
{
avgx = avgx + Coord[i][1];
avgy = avgy + Coord[i][2];
}
avgx = avgx / times;
avgy = avgy / times;
cout << "The AVG coord is:" << endl;
cout << "(" << avgx << "," << avgy << ")" << endl;// 显示输入坐标的均值
}
private:
float Coord[100][100]; // 存放输入坐标的数组
int times; // 存放输入坐标数目
};
int main()
{
Coordinate c(5);
c.InputCoord();
c.ShowCoord();
c.ShowAvgCoord();
return 0;
// 执行显示和坐标均值运算
}
//202130310286
构造函数的运行顺序为:先进入main函数,之后进入Coordinate()函数,默认两对坐标,先输入Coordinate construction1 called!,后转到void InputCoord()输入两对坐标,最后调用析构函数。
析构函数的运行顺序为:析构函数在程序执行完Return 0后执行,用于释放分配给对象的内存空间
在main函数中加入以下代码后
Coordinate y(5);
y.InputCoord();
y.ShowCoord();
y.ShowAvgCoord();
return 0;
增加到了五对坐标
运行结果如下
参考链接:https://blog.csdn.net/JJdeAHAO/article/details/127557736