C++ 通過虛擬參數區分前綴與後綴重載:
Type operator++() —— 前綴 ++a,無參數。Type operator++(int) —— 後綴 a++,帶 int 佔位參數(無實際意義)。int a = 5;
int c1 = ++a; // a 先增為 6,c1 = 6
int c2 = a++; // c2 = 6,a 後增為 7
前綴返回自增後的值(左值),後綴返回自增前的值(右值/臨時對象)。
#include <iostream>
using namespace std;
class Time {
int hours, minutes;
public:
Time(int h=0, int m=0) : hours(h), minutes(m) {}
void display() const { cout << "H " << hours << " M " << minutes << endl; }
// 前綴 ++:自增後返回自身引用
Time& operator++() {
++minutes;
if (minutes >= 60) { minutes -= 60; ++hours; }
return *this;
}
// 後綴 ++:保存舊值,自增,返回舊值副本
Time operator++(int) {
Time old(*this); // 複製當前狀態
++(*this); // 復用前綴邏輯
return old; // 返回副本
}
};
int main() {
Time T1(11, 59), T2(10, 40), T3, T4;
++T1; T1.display(); // H 12 M 0
++T1; T1.display(); // H 12 M 1
++T2; T2.display(); // H 10 M 41
T2++; T2.display(); // H 10 M 42
T3 = T2++; T3.display(); // H 10 M 42 (舊值)
T4 = ++T1; T4.display(); // H 12 M 2 (新值)
return 0;
}
| 特性 | 前綴 ++ | 後綴 ++ |
|---|---|---|
| 參數列表 | () | (int) |
| 返回類型 | 引用 Type& | 值 Type |
| 執行順序 | 先增後用 | 先用後增 |
| 性能 | 無臨時對象,高效 | 需構造臨時副本,稍慢 |
| 最佳實踐 | 優先使用 | 僅在需要舊值時使用 |
*this 引用,支持鏈式調用。++(*this),避免代碼重複。