C++学习:explicit关键字

最近在尝试着看源码的时候碰到了explicit关键字,查阅资料后有了一些理解,于是来做下笔记:

explicit主要是用来修饰类的构造函数,从而使被构造的类只能发生显示转换,而不能进行隐式转化。

我们来看C++对象的显式和隐式转化:

 1     #include <iostream>
 2 
 3     using namespace std;
 4     
 5     class Test1{
 6         public:
 7             Test1(int n){  // 隐式构造函数
 8                 num = n;
 9             }
10         private:
11             int num;
12     };
13 
14     class Test2{
15         public:
16             explicit Test2(int n){   //explicit(显式)构造函数
17                 num = n;
18             }
19         private:
20             int num;
21     };
22 
23     int main(){
24         Test1 t1 = 10;  // 隐式转化
25         //等同于 Test1 temp(10);  Test1 t1 = temp; 
26         
27         Test1 t2 = 'c';  // 'c'被转化为ascii码,然后同上
28         
29         Test2 t3 = 12;  // 编译错误,不能隐式调用其构造函数
30         
31         Test2 t4 = 'c';  // 编译错误,不能隐式调用其构造函数
32         
33         Test2 t5(10);  //  正常的显式转化
34         return 0;
35     }

总结:explicit关键字只用于类的单参数构造函数,对于无参数和多参数的构造函数总是显示调用,因此使用explicit没有意义。通常情况下,我们约定对于单参数构造函数必须使用explicit关键字,避免产生意外的类型转化,拷贝构造函数除外。

原文地址:https://www.cnblogs.com/Satan666/p/12663580.html