C++的explicit

今天早上突然看到一个代码中出现了explicit这个关键字。

之前没有接触到这个,感觉很生疏。就百度去查了下使用方法。

下面我用一个例子来解释explicit的功能。

 1 class Test1
 2 {
 3     public:
 4         Test1(int n){
 5             num = n;
 6         }
 7     private:
 8         int num;
 9 };
10 
11 class Test2
12 {
13     public:
14         explicit Test2(int n){
15             num = n;
16         }
17     private:
18         int num;
19 };
20 
21 int main(){
22     Test1 t1 = 12;
23     //Test2 t2 = 12;
24     Test2 t3(12);
25     return 0;
26 }

Test2类中的构造函数使用了explicit这个关键字来做修饰。意思是调用Test2的构造函数必须使用显示的调用方法。就如同代码中line 24的显示调用方法。而line 23的调用方法将会导致编译错误。但是Test1类的构造方法是可以有隐式转换的,line 22证实了隐式调用构造函数的可能。

 

posted @ 2013-04-17 11:10  专属9号  阅读(133)  评论(0编辑  收藏  举报