3.1坐标上机作业(202130310149)

#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.一个对象被定义在函数体内,当这个函数被调用结束时,调用析构函数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值