Explicit: detailed, clear, explicit, undisguised, explicit, external, clear, straightforward, (rent, etc) direct payment.
In C + +, a constructor of a parameter (or a multiple-parameter constructor with a default value except for the first argument) takes two roles. 1 is a constructor, and 2 is a default and implied type conversion operator. So, sometimes when we write code such as AAA = XXX, and exactly the type of XXX is the parameter type of the AAA single parameter constructor, the compiler automatically invokes the constructor and creates a AAA object. This looks like a cool, very convenient. But in some cases (see the authoritative example below), it violates our (Programmer's) intent. This is the time to add a explicit modifier to the constructor, specifying that the constructor can be invoked only explicitly, and cannot be used implicitly as a type conversion operator. Oh, it seems to be aboveboard some better. Explicit constructor function resolution: Explicit constructors are used to prevent implicit conversions. Take a look at the following code:
Class Test1
{public
:
Test1 (int n) {num = n;}//Normal constructor
private:
int num;
};
Class Test2
{public
:
explicit Test2 (int n) {num = n;}//explicit (Explicit) constructor
private:
int num;
};
int main ()
{
Test1 t1 = 12;//implicitly calls its constructor, succeeds
Test2 t2 = 12;//Compilation error, cannot implicitly call its constructor
Test2 T3 (12); 18/>return 0;
}
The Test1 constructor takes an int parameter, and the code 17 line is implicitly converted to this constructor that calls Test1. The Test2 constructor is declared as explicit (explicit), which means that the constructor cannot be invoked through an implicit conversion, so there is a compilation error in the code 18 line. An ordinary constructor can be called implicitly. The explicit constructor can only be displayed for invocation.