The explicit keyword is used to modify the constructor of a class, indicating that the constructor is displayed, relative to the implicit keyword.
First of all, this keyword can only be used in the constructor declaration within the class, but not in the function definition outside of the class, and its role is not implicit conversion.
Copy Code code as follows:
Class Gxgexplicit//classes with no keyword explicit
{
Public
int _size;
gxgexplicit (int size)
{
_size = size;
}
};
Here is the call to
Gxgexplicit gE1 (24); This is no problem.
Gxgexplicit gE2 = 1; This is no problem.
Gxgexplicit gE3; This is not going to work, there is no default constructor
GE1 = 2; This is no problem.
gE2 = 3; This is no problem.
gE2 = gE1; This is no problem.
But if gxgexplicit modified to stack, our _size represents the size of the stack, then the second sentence of the call is neither fish nor fowl, and easy to doubt. This is not a form that allows code readers to understand and accept, although it is legal (compilers can compile). This is because the compiler has implicit conversion functionality by default, and you enter gE2 = 1 to compile the same result as the first sentence. So, explicit came in handy. Modify the code as:
Copy Code code as follows:
Class Gxgexplicit
{
Public
int _size;
explicit gxgexplicit (int size)
{
_size = size;
}
};
Continue with the above call:
Gxgexplicit gE1 (24); This is no problem.
Gxgexplicit gE2 = 1; This is not going to work, the keyword cancels the implicit conversion
Gxgexplicit gE3; This is not going to work, there is no default constructor
GE1 = 2; This is not going to work, the keyword cancels the implicit conversion
gE2 = 3; This is not going to work, the keyword cancels the implicit conversion
gE2 = gE1; This is not possible, the keyword cancels the implicit conversion, unless the class implements the overload of the operator "=".
This is the compiler (VS2005) display: cannot convert from ' int ' to ' gxgexplicit '.
You can see from here that the function of this keyword is to mask the implicit conversion of the compiler.
An attention point on MSDN describes the fact that implicit conversions are automatically canceled when the constructor argument exceeds two. For example
Copy Code code as follows:
Class Gxgexplicit
{
Private
int _size;
int _age;
Public
Explicit gxgexplicit (int age,int size)
{
_age = age;
_size = size;
}
};
This is no keyword effect is the same. That is the equivalent of having this keyword.
But the other exception: there is only one parameter that must be entered, and the rest is a parameter with a default value.
Copy Code code as follows:
Class Gxgexplicit
{
Private
int _size;
int _age;
Public
Explicit gxgexplicit (int age,int size = 0)
{
_age = age;
_size = size;
}
};
Class Gxgexplicit
{
Private
int _size;
int _age;
int _hight;
Public
Explicit gxgexplicit (int age,int size = 0)
{
_age = age;
_size = size;
_hight = hight;
}
};