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);

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

相关文章:

  • 2021-05-23
  • 2021-11-10
  • 2021-09-16
  • 2022-01-05
  • 2021-06-05
  • 2021-07-20
  • 2021-06-12
猜你喜欢
  • 2021-08-21
  • 2021-09-18
  • 2021-07-11
  • 2021-12-21
  • 2022-01-30
  • 2021-12-04
  • 2021-06-05
相关资源
相似解决方案