1.explicit类型的构造函数和普通类型的构造函数的区别
普通的构造函数可以被显式调用和隐试调用,但是explicit的构造函数只能被显式的调用,不能被隐试的调用。代码示例如下:
class test0{
private:
int i;
public:
explicit test0(int n)
{
i = n;
cout << "i = " << i << endl;
}
};
class test1{
private:
int j;
public:
test1(int n)
{
j = n;
cout << "j = " << j << endl;
}
};
int main(int argc, char *argv[])
{
//test0 t0 = 34;//这种就是隐试调用,只能是普通的构造函数,也就是构造函数前没有加explicit,否者会编译出错
test0 t0(34);//如果explicit类型的构造函数的,只能够像这样显示的调用构造函数
test1 t1 = 55;
while (1);
return 0;
}
2.explicit的作用
分析如下代码
#include <iostream>
#include <string>
using namespace std;
class test1{
public:
string type;
test1() :type("void"){}
explicit test1(short) :type("short"){}//2.由于这里使用了explicit,所以不能够