zoukankan      html  css  js  c++  java
  • c++ explicit

    http://zh.cppreference.com/w/cpp/language/explicit

     

    explicit 指定符

     
     
     
     

    explicit 指定符指定构造函数或转换函数 (C++11 起)不允许隐式转换复制初始化。它仅可出现于在其类中定义的这种函数的 decl-specifier-seq 中。

    注意

    声明不带有函数指定符 explicit 的拥有单个非默认参数的 (C++11 前)构造函数被称作转换构造函数

    构造函数(除了复制/移动)和用户定义转换函数都可以是函数模板; explicit 的含义不变。

    示例

    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 进行直接初始化
    }
  • 相关阅读:
    面向对象
    标准库内置模块
    json迭代器生成器装饰器
    基本数据操作
    列表元组字典字符串操作
    深入了解Spring之IoC
    认识OAuth 2.0及实例
    web.xml中context-param和init-param的区别
    虚拟机centos6网卡配置及提示Device does not seem to be present
    JUC之深入理解ReentrantReadWriteLock
  • 原文地址:https://www.cnblogs.com/l2017/p/6905470.html
Copyright © 2011-2022 走看看