【问题标题】:"Explicit" preventing automatic type conversion? [duplicate]“显式”阻止自动类型转换? [复制]
【发布时间】:2013-01-03 06:36:49
【问题描述】:

可能重复:
What does the explicit keyword in C++ mean?

我不明白以下内容。如果我有:

class Stack{
    explicit Stack(int size);
}

没有关键字explicit 我可以这样做:

Stack s;
s = 40;

如果没有提供明确的说明,为什么我可以执行上述操作?是不是因为这是堆栈分配(无构造函数),而 C++ 允许将任何内容分配给变量,除非使用 explicit

【问题讨论】:

标签: c++


【解决方案1】:

嘿,它很简单。 显式关键字仅阻止编译器将任何数据类型自动转换为用户定义的类型。它通常与具有单个参数的构造函数一起使用。 所以在这种情况下,你只是阻止编译器进行显式转换

#include iostream
 using namespace std;
class A
{
   private:
     int x;
   public:
     A(int a):x(a)
      {}
}
 int main()
{
A b=10;   // this syntax can work and it will automatically add this 10 inside the 
          // constructor
return 0;
}
but here

class A
{
   private:
     int x;
   public:
    explicit A(int a):x(a)
      {}
}
 int main()
{
A b=10;   // this syntax will not work here and a syntax error
return 0;
}

【讨论】:

    【解决方案2】:

    这一行

    s = 40;
    

    等价于

    s.operator = (40);
    

    尝试匹配默认的operator = (const Stack &)。如果Stack 构造函数不显式,则尝试以下转换并成功:

    s.operator = (Stack(40));
    

    如果构造函数是explicit,则不尝试此转换,重载解析失败。

    【讨论】:

    • s.operator = (Stack(40)); 有什么问题?这不合法吗?我们只是想阻止分配 40 号?
    • @user997112: s.operator = (Stack(40)) 是合法的,但它是对构造函数的显式调用。关键是如果构造函数被称为explicit,则不会尝试此版本。
    猜你喜欢
    • 2011-09-15
    • 1970-01-01
    • 2012-02-15
    • 2012-02-24
    • 2019-06-01
    • 2016-06-03
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    相关资源
    最近更新 更多