C++支援運算子多載 (operator overloading) 允許自定義型態的運算子行為:
class Grade {
public:
Grade() { data_ = 0;}
Grade(int v) { data_ = v; }
void Set(int v) { data_ = v; }
int Get() const { return data_; }
private:
int data_;
};
const Grade operator+(const Grade &lhs, const Grade &rhs) {
return lhs.Get() + rhs.Get();
}
Grade c = a + b;
a + b 運算時會試著呼叫operator+(a, b);
但因為 a 是類別型態,所以也會試著呼叫 a.operator+(b);
而且後者的優先順序比較高。
bool operator>=(const Grade &lhs, const Grade &rhs) {
bool RetOutcome = lhs.Get() >= rhs.Get();
return RetOutcome;
}
文章標籤
全站熱搜
