賦予自定義類型使用內置運算符(+ - * / == << 等)的能力,實現語法糖。本質是函數重載,函數名為 operator@。
*this,參數少一個。Point operator+(const Point& rhs) const;friend。friend int operator*(const Point&, const Point&);class Point {
int x, y;
public:
Point(int _x, int _y): x(_x), y(_y) {}
// 成員函數:向量加
Point operator+(const Point& p) const {
return Point(x + p.x, y + p.y);
}
// 友元函數:內積
friend int operator*(const Point& a, const Point& b) {
return a.x*b.x + a.y*b.y;
}
};
// 使用
Point p1(1,3), p2(2,6);
Point p3 = p1 + p2; // (3,9)
int dot = p1 * p2; // 20
. .* :: sizeof ?: typeid。&& ||、逗號 ,、取址 &(除非極特殊需求),因會失去短路求值/內置語義。=、下標 []、調用 ()、箭頭 -> **必須**作為成員函數重載。T& operator++() 無參數,返回引用。T operator++(int) 佔位參數 int,返回舊值副本。class Array {
int* a; int pos, n;
public:
int& operator++() { return a[++pos]; } // ++a
int operator++(int) { return a[pos++]; } // a++
};
+ 應無副作用,+= 修改左值。== 應重載 !=;< 配 > 等。<< >> 必須為友元(左操作數是流)。操作符重載是 C++ 表達力的核心。正確使用能讓自定義類型像內置類型一樣自然運算。關鍵在於選擇成員/友元、保持語義一致、避免濫用邏輯運算符。