最近在尝试着看源码的时候碰到了explicit关键字,查阅资料后有了一些理解,于是来做下笔记:
explicit主要是用来修饰类的构造函数,从而使被构造的类只能发生显示转换,而不能进行隐式转化。
我们来看C++对象的显式和隐式转化:
#include <iostream>
using namespace std;
class Test1{
public:
Test1(int n){ // 隐式构造函数
num = n;
}
private:
int num;
};
class Test2{
public:
explicit Test2(int n){ //explicit(显式)构造函数
num = n;
}
private:
int num;
};
int main(){
Test1 t1 = 10; // 隐式转化
//等同于 Test1 temp(10); Test1 t1 = temp;
Test1 t2 = 'c'; // 'c'被转化为ascii码,然后同上
Test2 t3 = 12; // 编译错误,不能隐式调用其构造函数
Test2 t4 = 'c'; // 编译错误,不能隐式调用其构造函数
Test2 t5(10); // 正常的显式转化
return 0;
} 总结:explicit关键字只用于类的单参数构造函数,对于无参数和多参数的构造函数总是显示调用,因此使用explicit没有意义。通常情况下,我们约定对于单参数构造函数必须使用explicit关键字,避免产生意外的类型转化,拷贝构造函数除外。

京公网安备 11010502036488号