"Explicit" preventing automatic type conversion?

Possible Duplicate:
What does the explicit keyword in C++ mean?

I do not understand the following. If I have:

class Stack{
    explicit Stack(int size);
}

without the keyword explicit I would be allowed to do:

Stack s;
s = 40;

Why would I be allowed to do the above if explicit wasn't provided?? Is it because this is stack-allocation (no constructor) and C++ allows anything to be assigned to the variable unless explicit is used?


This line

s = 40;

is equivalent to

s.operator = (40);

Which tries to match the default operator = (const Stack &) . If the Stack constructor is not explicit, then the following conversion is tried and succeeds:

s.operator = (Stack(40));

If the constructor is explicit then this conversion is not tried and the overload resolution fails.


hey its pretty simple . the explicit key word only stops complier from automatic conversion of any data type to the user defined one.. it is usually used with constructor having single argument . so in this case u are jus stopping the complier from explicit conversion

#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;
}
链接地址: http://www.djcxy.com/p/24558.html

上一篇: C ++显式构造函数,需要一个指针

下一篇: “显式”阻止自动类型转换?