#include <iostream>
using namespace std;
int count_nr;
class Coordinate {
public:
Coordinate();
Coordinate(int times1);
Coordinate(int x1, int x2,int y1,int y2);
~Coordinate();
void InputCoord();
void ShowCoord();
void ShowAvgCoord();
private:
float Coord[100][100];
int times;
};
int main()
{
//1.
//Coordinate x;
//x.InputCoord();
//x.ShowCoord();
//x.ShowAvgCoord();
//2.
//Coordinate y(5);
//y.InputCoord();
//y.ShowCoord();
//y.ShowAvgCoord();
//3使用对象数组
//Coordinate fun[4];
//fun[0].InputCoord();
//fun[0].ShowCoord();
//fun[0].ShowAvgCoord();
//4.赋值式定义
//Coordinate fun={1, 2, 5, 4};
//5.先定义后赋值
//Coordinate x;
//x = { 1,2,5,4};
//6.多重花括号赋值
//Coordinate fun[4]={{1,2,5,4},{1,2,5,8},{4,5,2,6}};
return 0;
}
Coordinate::Coordinate()
{
times = 2;
cout << "Coordinate construction1 called" << endl;
count_nr++;
cout << count_nr << endl;
}
Coordinate::Coordinate(int times1)
{
times = times1;
cout << "Coordinate construction2 called" << endl;
count_nr++;
cout << count_nr << endl;
}
Coordinate::~Coordinate()
{
cout << "Coordinate destruction called!" << endl;
count_nr--;
cout << count_nr << endl;
}
void Coordinate::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 Coordinate::ShowCoord()
{
cout << "The coord is:" << endl;
for (int i = 0; i < times; i++)
{
cout << "(" << Coord[i][1] << "," << Coord[i][2] << ")" << endl;
}
}
void Coordinate::ShowAvgCoord()
{
float avgx = 0;
float avgy = 0;
for (int i = 0; i < times; i++)
{
avgx += Coord[i][1];
avgy += Coord[i][2];
}
avgx /= times;
avgy /= times;
cout << "The AVG coord is:" << endl;
cout << "(" << avgx << "," << avgy << ")" << endl;
}
Coordinate::Coordinate(int x1, int x2, int y1, int y2) {
float avgx = 0;
float avgy = 0;
avgx = (x1 + x2) / 2.0;
avgy = (y1 + y2) / 2.0;
cout << "(" << avgx << "," << avgy << ")" << endl;
count_nr++;
cout << count_nr << endl;
}
1.当主函数运行代码时,mian 函数中的Coordinate x新建了一个对象调用了一次构造函数(Coordinate::Coordinate()),count的值加一;
当主函数运行完时,调用了一次析构函数(Coordinate::~Coordinate())count的值减一;
2.当主函数运行代码时,mian 函数中的Coordinate y(5)新建了一个对象调用了一次构造函数(Coordinate::Coordinate(int times1)),times的值更新为5,count的值加一;这时函数可以对5个有二维坐标的事物求平均坐标;
当主函数运行完时,调用了一次析构函数(Coordinate::~Coordinate())count的值减一;
3.使用对象数组时,建立几次对象就调用了几次构造函数(Coordinate();),如Coordinate fun[4];就调用了四次构造函数。当主函数运行结束时就会调用几次析构函数。
4.赋值式定义 调用一次构造函数(Coordinate::Coordinate(int x1, int x2, int y1, int y2))
当主函数运行完时,调用了一次析构函数(Coordinate::~Coordinate())count的值减一;
5.先定义后赋值 先调用一次构造函数(Coordinate::Coordinate());赋值时调用一次构造函数(Coordinate::Coordinate(int x1, int x2, int y1, int y2));当主函数运行完时,调用了二次析构函数(Coordinate::~Coordinate())count的值减二;
6.多重花括号赋值 建立几次对象就调用了几次构造函数(Coordinate::Coordinate(int x1, int x2, int y1, int y2)),如Coordinate fun[4]={{1,2,5,4},{1,2,5,8},{4,5,2,6}};就调用了四次构造函数。当主函数运行结束时就会调用几次析构函数。
总结:主函数开头调用了几次构造函数(定义时与赋值时),主函数运行完后就会调用几次析构函数。