码迷,mamicode.com
首页 > 其他好文 > 详细

explict关键字

时间:2014-09-21 14:46:10      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   div   

【本文链接】

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关键字

标签:style   blog   http   color   io   os   ar   for   div   

原文地址:http://www.cnblogs.com/hellogiser/p/explict.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!