#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 showaveragecoord()
{
float averagex = 0;
float averagey = 0;
for (int i = 0; i < times; i++)
{
averagex = averagex + coord[i][1];
averagey = averagey + coord[i][2];
}
averagex = averagex / times;
averagey = averagey / times;
cout << "the average coord is:" << endl;
cout << "(" << averagex << "," << averagey << ")" << endl;
}
private:
float coord[100][100];
int times;
};
int main()
{
coordinate y(5);
y.inputcoord();
y.showcoord();
y.showaveragecoord();
return 0;
}
本次上机实验正式开启了与C语言相比更加深入的“类与对象”模块,这对于我们来说也是一个挑战,“类与对象”是C++最具特色的地方,所以学好这个地方就等于成功了一半。对于这次上机实验,是输出一个二维数组和其中值,参照老师给出的代码程序,最后顺利的运行了出来,但中间所用的析构函数的表示~,在第一次调试中出了错误,还有在输出中值的代码段,由于averagex和averagey忘记定义变量,导致程序报错,于是我将其赋除值为0用来计算。也让我明白了析构函数是在主函数中分配给对象的存储空间的释放。这次上机实验,让我更深的理解了C++中“类与对象”的基本概念,大体掌握了类的声明和对象的定义以及所涉及构造函数和析构函数的生成方法。我的C语言基础比较薄弱,所以在初学的路上,应当跟着老师一步一步来,在理解的基础上加以摸索。