命名空间
变体
操作

explicit 说明符

来自 cppreference.cn
< cpp‎ | language
 
 
C++ 语言
 
 

目录

[编辑] 语法

explicit (1)
explicit ( expression ) (2) (自 C++20 起)
expression (表达式) - 语境转换的 bool 类型的常量表达式


1) 指定构造函数或转换函数(自 C++11 起)推导指引(自 C++17 起)是显式的,即它不能用于隐式转换复制初始化
2) explicit 说明符可以与常量表达式一起使用。当且仅当该常量表达式求值为 true 时,该函数才是显式的。
(自 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 起)
特性测试宏 Std 特性
__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
}

[编辑] 参见