| 類別 | 運算子 | 範例 |
|---|---|---|
| 算術 | + - * / | x = y + z; |
| 賦值 | = += -= *= /= &= |= | x += 10; // x = x + 10 |
| 邏輯 | && || | if (x && 0xFF) |
| 關係 | == != < > <= >= | if (x >= 10) |
| 一元 | * & ~ ! ++ -- | int* p = &y; ++x; |
| 類/結構 | :: | MyClass::StaticFunc(); |
| -> | ptr->MemberFunc(); | |
| . | obj.MemberFunc(); |
int x = 10;
cout << x++; // 輸出 10,x 變 11
cout << x; // 輸出 11
cout << ++x; // x 先變 12,輸出 12
++x:先遞增,回傳新值(引用),效率略高。x++:先回傳舊值(暫存副本),再遞增。同一符號語義隨上下文變化:* 可為乘號、指標宣告、解參考。
可自訂型別行為:
class Complex {
public:
Complex operator+(const Complex& rhs) const; // a + b
Complex& operator++(); // 前置 ++a
};
屬進階主題,本書不深入,但理解「運算子本質是函數」有助閱讀標準庫代碼。
int Multiply(int x, int y) { // 返回型別 函數名 參數列
int z = x * y; // 函數體
return z; // 返回語句
}
// .h 或檔案頂部
int multiply(int, int);
void showResult(int);
// .cpp 或 main 之後
int multiply(int x, int y) { return x * y; }
void showResult(int res) { cout << "Result: " << res << endl; }
result = multiply(2, 5); // 字面值
result = multiply(x, y); // 變數
showResult(multiply(x, y)); // 巢狀調用
multiply(x, y); // 忽略返回值(合法,但可能丟失錯誤碼)
經典範例:階乘、樹遍歷。需設定基底案例防止無限遞迴導致堆疊溢位。