C++中explicit的用法

C++提供了关键字explicit,可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生,声明为explicit的构造函数不能在隐式转换中使用

例子:

#include <iostream>
using namespace std;

class A
{
public:
    A(int i = 5)
    {
        m_a = i;
     }
private:
    int m_a;
};

int main()
{
    A s;
    //我们会发现,我们没有重载'='运算符,但是去可以把内置的int类型赋值给了对象A.
    s = 10;
    //实际上,10被隐式转换成了下面的形式,所以才能这样.
    //s = A temp(10);

    system("pause");
    return 0;
}

先设置端点、之后按F5进入调试、s的值从默认的5变成了10. 

C++中explicit的用法

当类构造函数的参数只有一个的时候,或者所有参数都有默认值的情况下,类A的对象时可以直接被对应的内置类型隐式转换后去赋值的,这样会造成错误,所以接下来会体现出explicit这个关键词的作用.


#include <iostream>
using namespace std;
class Test1
{
public :
	Test1(int num):n(num){}
private:
	int n;
};
class Test2
{
public :
	explicit Test2(int num):n(num){}
private:
	int n;
};
 
int main()
{
	Test1 t1 = 12;
	Test2 t2(13);
	Test2 t3 = 14;
		
	return 0;

}

会指出 t3那一行error:无法从“int”转换为“Test2”。而t1却编译通过。注释掉t3那行,调试时,t1已被赋值成功。

注意:当类的声明和定义分别在两个文件中时,explicit只能写在在声明中,不能写在定义中。