讓自訂類別 (如 SmallInt) 能隱式參與內建型別 (int, double) 的運算,避免為每種運算子重載提供所有組合 (如 operator+ 需 6 個版本支援 SmallInt+int, int+SmallInt, SmallInt+SmallInt 等)。
class SmallInt {
int val;
public:
SmallInt(int i = 0) : val(i) {}
// 型別轉換函數:無返回型別、無參數
operator int() const { return val; } // SmallInt -> int
operator double() const { return val; } // SmallInt -> double
};
const (不修改物件)。explicit (C++11) 防止隱式轉換,僅允許 static_cast/扁式轉換。SmallInt si(5); int i = si; // 調用 operator int()void f(int); f(si); // 調用 operator int()si + 3 // si 轉 int 後執行 int+intclass Number {
public:
Number(const SmallInt& si); // SmallInt -> Number (隱式)
explicit Number(double d); // double -> Number (僅顯式)
};
explicit 禁止隱式轉換,僅允許直接初始化/強制轉換。若轉換函數目標型別與需求型別不完全匹配,但可經**標準轉換**到達,編譯器仍會調用:
extern void calc(double);
SmallInt si(10);
calc(si); // 1. si.operator int() → int
// 2. int → double (標準轉換)
// 調用 calc(double)
class A { public: operator int() const; };
class B { public: B(int); }; // 隱式轉換建構函數
void f(int);
void f(B);
A a;
f(a); // 錯誤:Ambiguous
// 路徑1: A::operator int() → f(int)
// 路徑2: A::operator int() → int → B(int) → f(B)
explicit、刪除轉換函數/建構函數)。static_cast 明確指定路徑。explicit 於單引數建構函數與轉換函數 (C++11),除非極確定隱式轉換符合領域邏輯且無歧義 (如智慧指標 operator bool())。to_string(), to_int() 等**顯式命名函數** 替代隱式轉換,提高可讀性。const,確保不修改物件狀態。