高手解释一下这几句c++代码

来源:百度知道 编辑:UC知道 时间:2024/06/04 18:47:38
题目要求:定义一个计数器类counter,要求对其运算符”+”重载
#include<iostream.h>
class counter
{
int n;
public:
counter(){n=0;}
counter(int i){n=i;}
counter operator+(counter c)
{
counter temp;
temp.n=n+c.n;
return temp;
}
void disp()
{
cout<<"n="<<n<<endl;
}
};
void main()
{
counter c1(5),c2(10),c3;
c3=c1+c2;
c1.disp();
c2.disp();
c3.disp();
}

这是题目给的.但是我有几句不明白.
public:
counter(){n=0;}
counter(int i){n=i;}
counter operator+(counter c)
{
counter temp;
temp.n=n+c.n;
return temp;
}
还有和这几句
void main()
{
counter c1(5),c2(10),c3;
c3=c1+c2;
c1.disp();
c2.disp();
c3.disp();
}

是什么意思.能一一解释给我吗.谢谢了.还有我运行后没有反应.要让它有反应怎么改??

#include<iostream.h>
class counter
{
int n;
public:
counter(){n=0;}
counter(int i){n=i;}
//运算符+重载 因为你定义的类,系统不知道怎么+,所以要自己定义
//因为你的重载函数定义在内部,所以一个参数就可以了
//如果定义为友函数就要两个参数
counter operator+(counter c) //
{
counter temp; //定义一个counter类的对象
temp.n=n+c.n; //这里的n其实是this.n,this可以省略
return temp; //返回对象
}
void disp()
{
cout<<"n="<<n<<endl;
}
};
void main()
{
counter c1(5),c2(10),c3; //定义counter类型的变量 前两个定义
//第二个调用构造函数,第三个调用第一个构造函数
c3=c1+c2;
//分别调用各个对象的dis()函数,输出结果
c1.disp();
c2.disp();
c3.disp();
}