Usage of explicit in C++

C++ provides the keyword explicit to prevent the occurrence of implicit conversions that should not be allowed by the conversion constructor. Constructors declared as explicit cannot be used in implicit conversions. In C++, a one-argument constructor (or a multi-argument constructor with default values ​​for all but the first argument), assumes two roles:

1 is a construct;

2 is a default and implicit type conversion operator.

Therefore, sometimes when we write code such as AAA = XXX, and the type of XXX happens to be the parameter type of the AAA single-parameter constructor, the compiler will automatically call this constructor to create an AAA object.

This looks cool and convenient. But in some cases, it goes against the programmer's intent. At this time, the explicit modification should be added to the constructor, specifying that the constructor can only be explicitly called/used, and cannot be implicitly used as a type conversion operator. Analysis: The explicit constructor is used to prevent implicit conversions. See the code below: 

#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;
}

When compiling, it will point out the line t3 error: cannot convert from 'int' to 'Test2'. And t1 is compiled and passed. Comment out the line t3, when debugging, t1 has been assigned successfully.

Note: When the class declaration and definition are in two files, explicit can only be written in the declaration, not in the definition. 

Reprinted from: https://blog.csdn.net/qq_35524916/article/details/58178072

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324361889&siteId=291194637