2013-01-19 49 views
-3

可能重复:
What does the explicit keyword in C++ mean?“显式”阻止自动类型转换?

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

class Stack{ 
    explicit Stack(int size); 
} 

而不需要通过关键字explicit我将被允许做的事情:

Stack s; 
s = 40; 

为什么我会被允许做上述明确的,如果没有提供?是因为这是堆栈分配(无构造函数),并且C++允许将任何东西分配给变量,除非使用explicit

+1

使用搜索:http://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-in-c-意思是 – dans3itz

+0

我没有问清楚什么是明确的意思,我问为什么它可能被分配到40 ... – user997112

回答

5

此行

s = 40; 

相当于

s.operator = (40); 

它试图匹配默认operator = (const Stack &)。如果Stack构造不明确,那么下面的转换尝试和成功:

s.operator = (Stack(40)); 

如果构造是explicit那么这种转换没有试过和重载解析失败。

+0

s.operator =(Stack(40))有什么问题; ?这是不是合法的,我们只是想防止数字40被分配? – user997112

+0

@ user997112:'s.operator =(Stack(40))'是合法的,但它是对构造函数的* explicit *调用。关键是如果构造函数被说成是'explicit',那么这个版本不会被尝试。 – ybungalobill

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