“明确”阻止自动类型转换?

时间:2013-01-19 19:02:39

标签: c++

  

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

我不明白以下几点。如果我有:

class Stack{
    explicit Stack(int size);
}

没有关键字explicit我将被允许这样做:

Stack s;
s = 40;

如果没有提供显式,为什么我会被允许这样做?是因为这是堆栈分配(没有构造函数),C ++允许将任何内容分配给变量,除非使用explicit吗?

2 个答案:

答案 0 :(得分:6)

这一行

s = 40;

相当于

s.operator = (40);

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

s.operator = (Stack(40));

如果构造函数为explicit,则不会尝试进行此转换,并且重载决策失败。

答案 1 :(得分: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;
}