### operator運算符重載的疑問？

Complex operator + (Complex & c2)

{

Complex c;

return c;               //此處返回局部變量c；

}

Complex & operetor + (Complex)

{

this->i=this->i+c2.i;

this->j=this->i+c2.j;

return *this;               //此處返回this

}

#include<iostream>
using namespace std;

class Complex
{
public:
double i;
double j;
Complex ()
{
this->i=0;
this->j=0;
}
Complex(double i,double j)
{
this->i=i;
this->j=j;
}
void show()
{
cout<<"this->i="<<this->i<<endl<<"this->j="<<this->j<<endl;
}
/*
Complex & operator + (const Complex &c2)
{
this->i=this->i + c2.i;
this->j=this->j + c2.j;
return *this;
}
*/
Complex operator + (Complex &c2)
{
Complex c;
c.i=this->i+c2.i;
c.j=this->j+c2.j;
return c;
}
};
void f1()
{
Complex c1(1.1,3.3);
Complex c2(2.2,4.4);
Complex c3=c1+c2;
c3.show();
}
int main()
{

f1();
return 0;
}

farsight@ubuntu:~/shell\$

farsight@ubuntu:~/shell\$ ./a.out
this->i=3.3

this->j=7.7

farsight@ubuntu:~/shell\$

#include<iostream>
using namespace std;

class Complex
{
public:
double i;
double j;
Complex ()
{
this->i=0;
this->j=0;
}
Complex(double i,double j)
{
this->i=i;
this->j=j;
}
void show()
{
cout<<"this->i="<<this->i<<endl<<"this->j="<<this->j<<endl;
}

Complex & operator + (const Complex &c2)
{
this->i=this->i + c2.i;
this->j=this->j + c2.j;
return *this;
}

/*
Complex operator + (Complex &c2)
{
Complex c;
c.i=this->i+c2.i;
c.j=this->j+c2.j;
return c;
}
*/
};
void f1()
{
Complex c1(1.1,3.3);
Complex c2(2.2,4.4);
Complex c3=c1+c2;
c3.show();
}
int main()
{

f1();
return 0;
}
farsight@ubuntu:~/shell\$ vi complex.cpp

farsight@ubuntu:~/shell\$ vi complex.cpp
farsight@ubuntu:~/shell\$ ./a.out
this->i=3.3
this->j=7.7

farsight@ubuntu:~/shell\$

Complex & operator+（Complex &c2）  這種重載方式可以加拷貝構造函數，但是打印結果又錯。

#include<iostream>
using namespace std;

class Complex
{
public:
double i;
double j;
Complex ()
{
this->i=0;
this->j=0;
}
Complex(Complex &zhang)
{
cout<<"copy"<<endl;
}
Complex(double i,double j)
{
this->i=i;
this->j=j;
}
void show()
{
cout<<"this->i="<<this->i<<endl<<"this->j="<<this->j<<endl;
}

Complex & operator + (const Complex &c2)
{
this->i=this->i + c2.i;
this->j=this->j + c2.j;
return *this;
}

/*
Complex operator + (Complex &c2)
{
Complex c;
c.i=this->i+c2.i;
c.j=this->j+c2.j;
return c;
}
*/
};
void f1()
{
Complex c1(1.1,3.3);
Complex c2(2.2,4.4);
Complex c3=c1+c2;
c3.show();
}
int main()
{

f1();
return 0;
}

farsight@ubuntu:~/shell\$

farsight@ubuntu:~/shell\$ ./a.out
copy
this->i=-0.0982316      //結果有錯，不知道為什么？
this->j=-3.46551e-42
farsight@ubuntu:~/shell\$