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$

實例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$ 



注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com