列如:
class Complex
{
int real,image;
public:
Complex(real=0,image=0):real(real),image(image){}
Complex operator +(complex& b)
{
Complex t;
t.real=real+b.real;
t.image=image+b.image;
return t;
}
void operator =(Complex& c)
{
real=c.real;
image=c.image;
}
void show(int i)
{
cout<<"c"<<i<<"="<<real<<"+"<<image<<"i"<<endl;
}
};
int main()
{
Complex c1(10,20),c2(12,24),c3;
c3=c1+c2;
c3.show(3);
}
class F//n为分子,f为分母
{
int n,f;
public:
F(int n=0,int f=1):n(n),f(f){}
F operator+(F& c)
{
F t;
t.n=n*c.f+c.n*n;
t.f=f*c.f;
return t;
}
friend ostream& operator<<(ostream& o,const F& f)
{
o<<f.n<<"/"<<f.f;
return o;
}
void operator =(F& c)
{
n=c.n;
f=c.f;
}
};
int main()
{
F c1(1,2),c2(2,3),c3;
c3=c1+c2;
cout<<"c3="<<c3<<endl;
}
这两个程序我感觉一样啊,为什么第一个会错,第二个没错,当第一个在=重载的时候的形参加const就对了(const Complex& c)
[
本帖最后由 chinawide 于 2013-1-22 13:06 编辑 ]