【C++ 基础】C++中的explicit

C++提供了关键字explicit,可以阻止不应该允许的经过转换构造函数进行的隐式转换的发生。声明为explicit的构造函数不能在隐式转换中使用。
C++中, 一个参数的构造函数(或者除了第一个参数外其余参数都有默认值的多参构造函数), 承担了两个角色。

1.是个构造器  2. 是个默认且隐含的类型转换操作符。
所以, 有时候在我们写下如 ClassA a = b, 这样的代码, 且恰好b的类型正好是ClassA单参数构造器的参数类型, 这时候编译器就自动调用这个构造器, 创建一个ClassA的对象。

#include "stdafx.h"

class Test1
{
public:
	Test1(int n) { num = n; } //普通构造函数
private:
	int num;
};

class Test2
{
public:
	explicit Test2(int n) { num = n; } //explicit(显式)构造函数
private:
	int num;
};

int _tmain(int argc, _TCHAR* argv[])
{
	Test1 t1 = 12; //隐式调用其构造函数。 12是 Test1的默认构造函数的参数类型,调用成功
	Test2 t2 = 12; //编译错误,不能隐式调用其构造函数
	Test2 t3(12); //显式调用成功
	return 0;
}
原文地址:https://www.cnblogs.com/justlikethat/p/3446290.html