C++/CLI中可以對運算符進行重載,但與本地C++有所區別。同時對于運算符重載,數值類和引用類也存在不同要求。下面以例子開始,了解C++/CLI中重載運算符的方法。
一、數值類中重載運算符
下面的例子重載了加法運算符。
value class Length { private: int feet; int inches; public: static initonly int inchesPerFoot = 12; Length(int ft, int ins) : feet(ft), inches(ins) {} virtual String^ ToString() override { return feet+L" feet "+inches+L" inches"; } Length operator+(Length len) { int inchTotal = inches + len.inches + inchesPerFoot*(feet + len.feet); return Length(inchTotal/inchesPerFoot, inchTotal%inchesPerFoot); } };
類的使用很簡單,方法如下
Length len1 = Length(6, 9);
Length len2 = Length(7, 8);
Console::WriteLine(L"{0} plus {1} is {2}", len1, len2, len1+len2);
上面重載的加法運算符也可通過靜態成員的方式實現。
static Length operator+(Length len) { int inchTotal = inches + len.inches + inchesPerFoot*(feet + len.feet); return Length(inchTotal/inchesPerFoot, inchTotal%inchesPerFoot); }
下面定義Length與數值的乘法重載運算符,它包括了數值*長度和長度*數值兩種情況。這也是二元操作的一個例子
value class Length { //... static Length operator*(double x, Length len); static Length operator*(Length len, double x); };
函數的定義如下
Length Length::operator*(double x, Length len) { int ins = safe_cast<int>(x*len.inches + x*len.feet*inchesPerFoot); return Length( ins/12, ins%12 ); } length Length::operator*(Length len, double x) { return operator*(x, len); }
下面定義遞增運算符,這是一個一元運算符,可用同一個函數來定義前綴遞增和后綴遞增運算,編譯器能夠自動的根據調用情況來判斷是先遞增還是后遞增。
static Length operator++(Length len) { ++len.inches; len.feet += len.inches/len.inchesPerFoot; len.inches %= len.inchesPerFoot; return len; }
二、引用類中重載運算符
在引用類中重載運算符的方法與數值類基本相同,主要區別是形參和返回值一般都是句柄。這里就不再贅述了。