第三次实验

第三次实验,第1张

第三次实验

第三次实验内容一

本次实验学习了类和对象的基本应用,深刻理解了析构函数的含义和用法。

代码如下: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 construction1 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://成员变量定义
int times;
float Coord[100][100];
};
int main()
{
Coordinate x;
x.InputCoord();
x.ShowCoord();
x.ShowAvgCoord();
Coordinate y(5);
y.InputCoord();
y.ShowCoord();
y.ShowAvgCoord();
return 0;
运行过程:首先调用含有默认值的构造函数,输入两组二维数据,然后显示这两组数据及平均值,然后调用含参数的构造函数,输入n(参数)组二维数据,然后显示这n组数据及平均值。最后调用析构函数。
特点:简单清晰,调用时刻恰当,没有多余的冲突。
本次实验较为简单 但细节上学要学习的东西很多,希望下一次实验可以独立自主的完成,将学到的知识应用起来。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5504190.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-12

发表评论

登录后才能评论

评论列表(0条)

保存