#include<iostream>
using namespace std;
class coordinate {
private:int times;//输入坐标数目
float coord[100][100];//输入坐标的数组
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++)//2次
{
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[1][1];
avgy = avgy + coord[1][2];
}
avgx = avgx / times;
avgy = avgy / times;
cout << "The AVG coord is:" << endl;
cout << "(" << avgx << "," << avgy << ")" << endl;
}
};
int main()
{
coordinate x;
x.inputcoord();
x.showcoord();
x.showavgcoord();//第一次
/*coordinate y(5);
y.inputcoord();
y.showcoord();
y.showavgcoord();
return 0;*/第二次
}
第一次:不在主函数内给times初值。
因为在主函数中用类名定义x,coordinate x;没有给初始值,所以调用构造函数(construction1),默认值为times=2。
之后进入void inputcoord,输入坐标,因为给了times初值为2,所以for循环内输入两组坐标。
之后进入void showcoord,显示出我输入的坐标。
之后进入void showavgcoord。
最后调用析构函数。
第二次:在主函数内给初值5
在主函数内用类名定义y(5)将5赋给times。所以调用给初值的函数(construction2)。
之后逐一进入函数中
最后调用析构函数。
总结归纳
1.构造函数在声明中不能给数据成员赋值
2.构造函数与类名相同,一个类只能有一个默认构造函数
3.在定义一个对象时(eg:coordinate x)构造函数会被自动执行。
4.每个类必有析构函数
5.在主函数结束时,对象被撤销时,系统会自动调用析构函数
6.一个对象被定义在函数体内,当这个函数被调用结束时,调用析构函数