C++关键词

explicit

显示定义、禁止编译器隐式发生用户转换、如下

class SmallInt {
public:
    SmallInt(int i){}
};

class Number {
public:
    Number(const SmallInt&);
};

如果不使用explicit的话、那么即使使用一个int的变量来初始化Number的构造函数也可以成立、编译器会首先调用SmallInt的构造函数、先使用int的变量初始化SmallInt、再把SmallInt的对象引用给Number的构造函数

int ok = 0;
Number(ok);

但如果加上关键字explicit的话、这样编译是错误的!只能够精确匹配SmallInt类型

class SmallInt {
public:
    SmallInt(int i){}
};

class Number {
public:
    explicit Number(const SmallInt&);
};

int error = 0;
Number(error);

 =========================================================

原文地址:https://www.cnblogs.com/klobohyz/p/2456610.html