C++中允许一种特殊的声明比变量的方式。在这种情况下,可以将一个对应于构造函数参数类型的数据直接赋值给类变量。编译器在编译时会自动进行类转换,将对应于构造函数参数类型的数据转换为类的对象。但是这种宽松的规则会破坏代码的可读性,并导致难以发现的错误。其实只要在构造函数前加上explicit则会禁止这种自动转换。要注意的是explicit只对构造函数起作用。
下面来举例说明。
#include<iostream>
using namespace std;
class Test
{
public:
Test(int x=1):val(x){}
int GetVal(void){return val;}
private:
int val;
};
main()
{
Test t1(1);
cout<<"t1.val="<<t1.GetVal()<<endl;
Test t2=2;
cout<<"t1.val="<<t2.GetVal()<<endl;
}
在以上代码中我们发现可以把数字“2”直接发给Test类型的对象t2。这就是c++编译器隐式转换的结果。
然后我们在构造函数之前加上explicit:
#include<iostream>
using namespace std;
class Test
{
public:
explicit Test(int x=1):val(x){}
int GetVal(void){return val;}
private:
int val;
};
main()
{
Test t1(1);
cout<<"t1.val="<<t1.GetVal()<<endl;
Test t2=2;
cout<<"t1.val="<<t2.GetVal()<<endl;
}
编译时会出现以下错误: