Recently, I am reviewing QT and preparing for a project. In the default code explicit Dialog (qwidget * parent = 0) generated by QT creator, there is such a keyword "Explicit ".
To modify the constructor. In the past, when I was writing a program in windows, I basically did not encounter this keyword. What is the use of this keyword?
The keyword "Explicit" can disable "Single-parameter constructor" from being used for automatic type conversion. It is not easy to understand this sentence. Here is a simple example.
// Main. cpp
# Include <iostream>
Using namespace STD;
Class Test
{
Public:
Test (int)
{
M_data =;
}
Void show ()
{
Cout <"m_data =" <m_data <Endl;
}
PRIVATE:
Int m_data;
};
Void main (void)
{
Test t = 2; // assign a constant to an object
T. Show ();
}
Compilation is successful. Execution result: m_data = 2.
Why? Originally, C ++ constructed a temporary object test (2) through implicit conversion and assigned it to T (the default constructor is called here, instead of the overloaded "= ", because this is when the object is created ). If you add the keyword "Explicit" to the constructor, the constructor changes to "explicit test (int A)". If you compile the constructor again, the compiler reports an error. In this case, we can only explicitly use the constructor test T = test (2 ).