C++ 中的 explicit 关键字是什么意思?


C++ 中的 explicit 关键字用于标记构造函数,以不隐式转换类型。例如,如果您有一个类 Foo −

class Foo {
public:
    Foo(int n); // allocates n bytes to the Foo object
    Foo(const char *p); // initialize object with char *p
};

现在如果你尝试

Foo mystring = 'x';

字符 'x' 被隐式转换为 int,然后将调用 Foo(int) 构造函数。但这不是预期结果。因此,为了防止这种情况并使代码不易出现错误,将构造函数定义为 explicit −

示例 

class Foo {
   public:
      explicit Foo (int n); //allocate n bytes
      Foo(const char *p); // initialize with string p
};

更新于: 2020-6-24

3K+ 浏览次数

开启您的职业生涯

完成课程即可获得认证

开始学习
广告
© . All rights reserved.