explicit),實現 其他類型 → 類類型 的隱式轉換。operator type(),實現 類類型 → 其他類型 的隱式轉換。class SmallInt {
public:
SmallInt(int i = 0) : val(i) { // 非 explicit,允許隱式轉換
if (i < 0 || i > 255) throw out_of_range("Bad SmallInt value");
}
private:
std::size_t val;
};
// 用法:
SmallInt si = 42; // 隱式調用 SmallInt(42)
si = 3; // 隱式調用 SmallInt(3) 然後賦值
if (si) { ... } // 隱式轉換為 bool(需定義 operator bool)
explicit 關鍵字(C++11)explicit SmallInt(int i = 0); 禁止隱式轉換,僅允許直接初始化:SmallInt si(42);、SmallInt si = SmallInt(42);。explicit 轉換運算符,僅在直接初始化、靜態轉換、條件表達式中生效。class SmallInt {
public:
operator int() const { return val; } // 隱式轉換為 int
explicit operator bool() const { return val != 0; } // C++11:僅用於條件判斷
private:
std::size_t val;
};
// 用法:
int i = si; // 隱式調用 operator int()
bool b = si; // 調用 explicit operator bool(),允許在 if、while、!、? : 中
// long l = si; // 錯誤:無隱式轉換為 long(需轉換為 int 再提升)
若類 A 有接受 B 的轉換構造,B 有轉換為 A 的運算符,會導致歧義:
struct A { A(const B&); };
struct B { operator A() const; };
void f(A);
B b; f(b); // 錯誤:歧義,既可 A(b) 也可 b.operator A()
explicit 封鎖不必要的方向。to_string()、as_int())替代隱式轉換。std::string:explicit 構造自 const char*(C++11 起),但提供 c_str() 顯式獲取 C 字符串。std::shared_ptr:explicit operator bool(),支持 if (ptr) 但禁止 int i = ptr;。std::chrono::duration:提供顯式轉換構造與 count() 成員,避免單位混淆。explicit,除非建模語義要求隱式。operator type(),條件判斷類型用 explicit operator bool()。string、shared_ptr、chrono 均採用顯式為主、隱式為輔的設計。