急问一道简单的C++的改错题

来源:百度知道 编辑:UC知道 时间:2024/06/21 14:24:12
请大大们帮忙看下这个C++程序有什么错误,具体应该如何改正,十分感谢

#include<iostream.h>
class Sample
{
int n;
Sample(const Sample&);
public:
Sample (i=0){n=i;}
void add(Sample s)
{
if (&s==this) // 不能自己相加,this是当前对象的指针
cout<<"自己不能相加"<<endl;
else n += s.n;
}
void disp(){ cout<<endl<<" n="<<n<<endl;}
};
void main()
{ Sample s(1),s1(2);
s.add(s1);
}

请指出具体错误和改正的写法,鞠躬~

//Vc++ 6.0调试通过
//强烈建议楼主以后写程序注意下代码的风格!
#include<iostream.h>
#include<windows.h>
class Sample
{
int n;
Sample(const Sample&);
public:
Sample (const int i)
{
n=i;
}
void add(Sample &s)
{
if (&s==this) // 不能自己相加,this是当前对象的指针
cout<<"自己不能相加"<<endl;
else n += s.n;
}
void disp()
{
cout<<endl<<" n="<<n<<endl;
}
};

void main()
{
Sample s(1),s1(2); //注意这里,1和2是int 类型!!!!!
s.add(s1);
s.disp();
system("pause");
}

因为Sample(const Sample&); 声明成私有,已经禁止了对象复制,因此
void add(Sample s)将出现编译错误,可以写成void add(Sample &s)即可。
另外Sample(i=0){n=i;}应该为Sample(int i=0){n=i;}