操作符重載 = 操作符 + 重載。C++ 允許為自定義類型賦予運算符新含義,體現多態特性。
class Point {
public:
int x, y;
Point(int _x, int _y) : x(_x), y(_y) {}
Point operator+(Point &p) {
return Point(this->x + p.x, this->y + p.y);
}
};
int main() {
Point p1(1,3), p2(2,6);
Point p3 = p1 + p2; // 調用 p1.operator+(p2)
cout << "p3:(" << p3.x << "," << p3.y << ")"; // 輸出 (3,9)
}
兩種方式:類成員函數 和 友元函數。
class Point {
public:
int x, y;
Point(int _x, int _y);
Point operator+(Point &p); // 成員函數,隱含 this 指針
friend int operator*(Point &p1, Point &p2); // 友元函數,需兩個參數
};
成員函數參數比運算元少一個(靠 this),友元函數需顯式提供所有操作數。
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
Point(int _x, int _y) : x(_x), y(_y) {}
Point operator+(Point &p) { // 向量加
return Point(this->x + p.x, this->y + p.y);
}
friend int operator*(Point &p1, Point &p2); // 內積
};
int operator*(Point &p1, Point &p2) {
return p1.x * p2.x + p1.y * p2.y;
}
int main() {
Point p1(1,3), p2(2,6);
cout << p1 * p2 << endl; // 20
Point p3 = p1 + p2;
cout << "p3:(" << p3.x << "," << p3.y << ")" << endl; // (3,9)
}
&&, || 會求值所有操作數)。.、::、sizeof、?:。前置返回引用,後置返回值並接受 int 佔位參數區分:
class Counter {
int val;
public:
Counter& operator++() { ++val; return *this; } // 前置 ++c
Counter operator++(int) { Counter t=*this; ++val; return t; } // 後置 c++
};