天天看點

C++運算符重載,複數類

/*複數類:CComplex;
C++ 的運算符重載:使對象的運算表現的和編譯器内置類型一樣。
*/
#include<iostream>
using namespace std;
class CComplex{
public:
    //這裡相當于定義了三個構造函數。
    CComplex(int r=0,int i=0):mreal(r),mimage(i){}
    CComplex operator+(const CComplex &src){//不能傳回對象的指針。
        return CComplex(this->mreal+src.mreal,this->mimage+src.mimage);
    }
    void show(){
        cout<<this->mreal<<"  "<<this->mimage<<endl;
    }

    /*
        ++運算符的重載
        operator++()前置++。前置++傳回的是引用
        operator++(int) 後置++;後置++傳回的是臨時對象。
    */
    CComplex & operator++(){
        mreal+=1;
        mimage+=1;
        return *this;//前置++
    }
    CComplex  operator++(int){
        return CComplex(mreal++,mimage++);
    }
private :
    int mreal;
    int mimage;
    friend CComplex operator+(const CComplex &x,const CComplex &y);
    friend ostream& operator<<(ostream&os,const CComplex &cmp);
};
CComplex operator+(const CComplex &x,const CComplex &y){
    return CComplex(x.mreal+y.mreal,x.mimage+y.mimage);
}
ostream& operator<<(ostream&os,const CComplex &cmp){
    cout<<"mreal:"<<cmp.mreal<<"   mimage:"<<cmp.mimage<<endl;;
}
int main(){
    CComplex cmp1(10,10);
    CComplex cmp2(20,20);
    CComplex cmp3=cmp1+cmp2;
    cmp3.show();
    CComplex cmp4=cmp1+20;
    cmp4.show();
    //編譯器在做對象運算的時候,會調用對象的運算符重載函數
    //優先調用成員方法;如果沒有成員方法,
    //就在全局作用域找合适的運算符重載函數。
    CComplex cmp5=20+cmp1;
    cmp5.show();
    cout<<cmp5;

    return 0;
}

           
c++

繼續閱讀