explicit
說明符
來自 cppreference.com
目錄 |
[編輯] 語法
explicit
|
(1) | ||||||||
explicit ( 表示式 ) |
(2) | (C++20 起) | |||||||
表示式 | - | 型別為 bool 的上下文轉換常量表達式 |
2) explicit 說明符可以與常量表達式一起使用。當且僅當該常量表達式求值為 true 時,該函式才是 explicit。
|
(C++20 起) |
explicit 說明符只能出現在其類定義中建構函式 或轉換函式(C++11 起) 的宣告的 decl-specifier-seq 中。
[編輯] 注意
未用函式說明符 explicit 宣告的建構函式 帶單個非預設引數的(C++11 前) 稱為 轉換建構函式。
建構函式(複製/移動除外)和使用者定義的轉換函式都可以是函式模板;explicit 的含義不變。
緊隨 explicit 的 struct S { explicit (S)(const S&); // error in C++20, OK in C++17 explicit (operator int)(); // error in C++20, OK in C++17 }; |
(C++20 起) |
功能測試宏 | 值 | 標準 | 特性 |
---|---|---|---|
__cpp_conditional_explicit |
201806L |
(C++20) | 條件 explicit |
[編輯] 關鍵詞
[編輯] 示例
執行此程式碼
struct A { A(int) {} // converting constructor A(int, int) {} // converting constructor (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: copy-initialization selects A::A(int) A a2(2); // OK: direct-initialization selects A::A(int) A a3 {4, 5}; // OK: direct-list-initialization selects A::A(int, int) A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int) A a5 = (A)1; // OK: explicit cast performs static_cast if (a1) { } // OK: A::operator bool() bool na1 = a1; // OK: copy-initialization selects A::operator bool() bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization // B b1 = 1; // error: copy-initialization does not consider B::B(int) B b2(2); // OK: direct-initialization selects B::B(int) B b3 {4, 5}; // OK: direct-list-initialization selects B::B(int, int) // B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int, int) B b5 = (B)1; // OK: explicit cast performs static_cast if (b2) { } // OK: B::operator bool() // bool nb1 = b2; // error: copy-initialization does not consider B::operator bool() bool nb2 = static_cast<bool>(b2); // OK: static_cast performs direct-initialization [](...){}(a4, a5, na1, na2, b5, nb2); // suppresses “unused variable” warnings }