c++ explicit key role

Concept introduction

Constructors can not only construct and initialize objects, but also have type conversion functions for constructors with a single parameter or with default values ​​except for the first parameter .

The explicit keyword can precisely prohibit the compiler's implicit type conversion.

1.explicit introduction

The role of explicit is to declare that the class constructor is called explicitly instead of implicitly.

Why modify the single parameter constructor?

Because the no-parameter constructor and the multi-parameter constructor themselves are called explicitly, there is no point in adding explicit.

1.1 Explicit calls and implicit calls

class Date
{
    
    
public:
	// 1.无参构造函数
	Date()
	{
    
    
		cout << "无参调用构造函数" << endl;
	}

	 //2. 单参构造函数
	Date(int year)
		:_year(year)
	{
    
    
		cout << "单参数调用构造函数" << endl;
	}

	//Date(int year, int month = 1, int day = 1)
	//	:_year(year)
	//	,_month(month)
	//	,_day(day)
	//{
    
    
	//	cout << "多参构造函数调用" << endl;
	//}


private:
	int _year;
	int _month;
	int _day;
};


int main()
{
    
    
	Date d1;
	Date d1(1);  // 直接调用构造函数
	Date d2 = 1;  //隐是调用:隐式类型转换:构造+拷贝构造+优化 -> 直接调用构造
	return 0;
}

Explicit call: direct explicit call, such as Date d1 calling the no-parameter constructor; or Date d1(1) calling the single-parameter constructor.
Implicit call: If you don’t call it directly, the compiler will call it by itself. For example, if Date d2 = 1, the single-parameter constructor will be called implicitly.

1.2 explicit meaning

The above formula call seems to assign the int type data directly to the Date type. This kind of code has implicit type conversion. Although there is no error on the surface, if the program makes an error later, it will be difficult to troubleshoot the error.

Therefore, in order to prevent the possible risks caused by this implicit conversion, it is necessary to declare the single-parameter constructor to be explicitly called, that is, to prohibit implicit calls, and just add explicite. as follows:

Insert image description here
Insert image description here
Insert image description here

It can be seen from here that explicit prohibits implicit conversion, making the program more robust.

Guess you like

Origin blog.csdn.net/weixin_45153969/article/details/132788433