explicit 指定符
單詞意思:
explicit : 明確的,清楚的
implicit : 含蓄的,暗示的。
- 指定構造函數或轉換函數 (C++11 起)爲顯式,即它不能用於隱式轉換和複製初始化。
- explicit 指定符可以與常量表達式一同使用。函數若且唯若該常量表達式求值爲 true 才爲顯式。
(C++20 起)
explicit 指定符只可出現於構造函數或轉換函數 (C++11 起)在其類定義內的 decl-specifier-seq 內。
示例
struct A
{
A(int) { } // 轉換構造函數
A(int, int) { } // 轉換構造函數 (C++11)
operator bool() const { return true; }
};
struct B
{
explicit B(int) { }
explicit B(int, int) { }
explicit operator bool() const { return true; }
};
int main()
{
A a1 = 1; // OK :複製初始化選擇 A::A(int)
A a2(2); // OK :直接初始化選擇 A::A(int)
A a3 {4, 5}; // OK :直接列表初始化選擇 A::A(int, int)
A a4 = {4, 5}; // OK :複製列表初始化選擇 A::A(int, int)
A a5 = (A)1; // OK :顯式轉型進行 static_cast
if (a1) ; // OK :A::operator bool()
bool na1 = a1; // OK :複製初始化選擇 A::operator bool()
bool na2 = static_cast<bool>(a1); // OK :static_cast 進行直接初始化
// B b1 = 1; // 錯誤:複製初始化不考慮 B::B(int)
B b2(2); // OK :直接初始化選擇 B::B(int)
B b3 {4, 5}; // OK :直接列表初始化選擇 B::B(int, int)
// B b4 = {4, 5}; // 錯誤:複製列表初始化不考慮 B::B(int,int)
B b5 = (B)1; // OK :顯式轉型進行 static_cast
if (b2) ; // OK :B::operator bool()
// bool nb1 = b2; // 錯誤:複製初始化不考慮 B::operator bool()
bool nb2 = static_cast<bool>(b2); // OK :static_cast 進行直接初始化
}