operator运算符重载的疑问?

时间:2020-12-15 22:20:44

第一种重载方式:

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$

实例2:

#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$