首页 > 代码库 > explict关键字

explict关键字

【本文链接】

http://www.cnblogs.com/hellogiser/p/explict.html

【分析】

explicit 只对构造函数起作用,用来抑制隐式转换。

Suppose you have a class String

 C++ Code 
1
2
3
4
5
6
 
class String
{
public:
    String(
int n); // allocate n bytes to the String object
    String(const char *p); // initializes object with char *p
}

Now if you try

 C++ Code 
1
 
String mystring = ‘x‘//  String mystring = String(‘x‘);

the char ‘x‘ will be converted to int and will call String(int) constructor. But this is not what the user might have intended. So to prevent such conditions, we can define the class‘s constructor as explicit.

 C++ Code 
1
2
3
4
5
6
 
class String
{
public:
    
explicit String (int n); //allocate n bytes
    String(const char *p); // initialize sobject with string p
}

【参考】

http://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-in-c-mean

http://www.cnblogs.com/cutepig/archive/2009/01/14/1375917.html

 

explict关键字