名稱空間
變體
操作

explicit 說明符

來自 cppreference.com
< cpp‎ | 語言
 
 
C++ 語言
 
 

目錄

[編輯] 語法

explicit (1)
explicit ( 表示式 ) (2) (C++20 起)
表示式 - 型別為 bool 的上下文轉換常量表達式


1) 指定建構函式 或轉換函式(C++11 起)推導指引(C++17 起) 為 explicit,即它不能用於 隱式轉換複製初始化
2) explicit 說明符可以與常量表達式一起使用。當且僅當該常量表達式求值為 true 時,該函式才是 explicit。
(C++20 起)

explicit 說明符只能出現在其類定義中建構函式 或轉換函式(C++11 起) 的宣告的 decl-specifier-seq 中。

[編輯] 注意

未用函式說明符 explicit 宣告的建構函式 帶單個非預設引數的(C++11 前) 稱為 轉換建構函式

建構函式(複製/移動除外)和使用者定義的轉換函式都可以是函式模板;explicit 的含義不變。

緊隨 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

[編輯] 關鍵詞

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
}

[編輯] 參閱