class type implicit conversionsIf the constructor accepts only one argument, it actually defines the implicit conversion mechanism for converting to this type, and sometimes we call this constructor a transformation constructor (converting constructor). That is, a constructor that can be called by an argument defines a rule that implicitly converts the parameter type of the constructor to the class type. This implicit conversion is limited to one-step conversion (that is, not continuous conversion).
Class A {public
:
A (char c) {}
A (std::string s) {}
};
In Class A, the constructor that accepts char and the constructor that accepts string define the rules that implicitly convert from both types to type A. In other words, where we need to use a, we can use char or string as an alternative:
A A = "Hello";//Convert the string type to a type implicitly
In some cases, however, implicit type conversions violate the programmer's intent, so programmers do not want implicit type conversions to occur, and the explicit keyword plays a role.
ExplicitThe explicit keyword is primarily used on constructors, and the explicit keyword can block constructors from implicit type conversions.
Explicit A (char c) {}
After declaring the constructor as explicit, a A = "Hello"; This statement will not compile.
The keyword explicit is valid only for the constructor of one argument. Constructors that require multiple arguments cannot be used to perform implicit conversions, so you do not need to specify these constructors as explicit. You can use the explicit keyword only when declaring a constructor within a class, and you should not repeat it when you define the class outside.
can only be used for direct initialization
One scenario in which an implicit conversion occurs is when we perform a copy-form initialization (using =), at which point we can only use direct initialization instead of using the explicit constructor. Explicit initialization (coercion type conversion) Although the compiler does not use the explicit constructor for an implicit conversion process, we can explicitly force the conversion using the explicit constructor. After all, the C + + standard definition explicit keyword only blocks implicit conversions and does not restrict explicit conversions.
In short, an implicit type conversion occurs, unless it is intended to be exploited, or an implicit conversion often leads to errors in procedural logic that are difficult to detect. Therefore, in principle, all constructors should be modified with explicit, and then removed when the intention is used, which can reduce the occurrence of errors.
Part of this article is excerpted from the C + + Primer (Chinese version) Fifth edition