C++的運算子多載:使物件的運算表現得和編譯器內置型別一樣
如下代碼,如果T是整形,那很好理解,但是如果 T 是一個 Student 類, a + b ?怎么操作,兩個學生類怎么相加?
這個就是我們要說的運算子多載問題
template
T sum(T a,T b){
return a + b; // a.+(b) => a.operator+(b) operator+ 就是我們需要的函式
}
CComplex operator+(const CComplex &lhs, const CComplex &rhs){
reutrn CComlex(lhs.x+rhs.x,lhs.y+rhs.y);
// 由于不能再類外訪問CComplex的私有成員,所以我們可以加上友元
// 在CComplex 加上 firend CComplex operator+(const CComplex &lhs, const CComplex &rhs);
}
ostream & operator<<(ostream & cout, const CComplex & val){
cout<<"Complex = "<<val.x <<" "<<val.y<<endl;
return out
}
class CComplex{
public:
CComplex(int _x=1,int _y=1):x(_x),y(_y){}
Complex operator+(const CComplex & _com){
CComplex _comp;
_comp.x= this->x + _com.x
_comp.y= this->y +_com.y;
return _comp;
}
//后置++,回傳的是 + 之前的值
Complex operator++(int){
CComplex tep=*this;
x++;
y++;
return tep;
}
//前置++ 回傳加后的值
Complex & operator++(){
x++;
y++;
return *this;
}
//+=不需要回傳值
void operator+=(const CComplex & _value){
x=x+_value.x;
y=y+_value.y;
}
private:
int x;
int y;
firend CComplex operator+(const CComplex &lhs, const CComplex &rhs);
firend ostream & operator<<(ostream & cout, const CComplex & val) ;
}
int main(){
CComplex comp1(100,200);
CComplex comp2(1,2);
CComplex comp3=comp1 + comp2;
CComplex comp4=comp1 + 20;//comp1.operator+(CComplex tep) => comp1.operator+(將20轉為CComplex物件)
//這個時候編譯器會想辦法 把 20轉為CComplex物件,在上面的類中,可以轉,因為 CComplex(int _x=1,int _y=1) 有默認值
//所以上面代碼 會使用20創建一個CComplex 物件,然后 再讓他們相加
CComplex comp5=30 +comp1;//編譯報錯 30.operator+(CComplex tep) 整形數的加法運算子里面沒有operator+(CComplex tep) 編譯器不會把30轉為CComplex物件
//編譯器在做物件的運算的時候,會呼叫物件的運算子多載函式(優先呼叫成員方法),r如果沒有成員方法
//就會在全域作用域中找合適的運算子多載函式 所以 CComplex comp5=30 +comp1 編譯器
//當在整數中找不到成員方法是,還可以 ::operator+(30,comp1) 在全域作用域中找運算子多載函式
//就會呼叫全域作用域中的 CComplex operator+(const CComplex &lhs, const CComplex &rhs) 方法,
//所以如果希望CComplex comp5=30 +comp1;編譯通過,可以加上全域函式 CComplex operator+(const CComplex &lhs, const CComplex &rhs)
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/536849.html
標籤:其他
上一篇:C++ 讀取檔案及保留小數方法
