C ++ provides the keyword explicit to prevent implicit conversions that should not be allowed by conversion constructors.
Constructors declared as explicit cannot be used in implicit conversions.
In C ++, the constructor of a parameter assumes two roles. 1 is a constructor 2 is a default and implicit type conversion operator.
Therefore, sometimes, when we write such as AAA = xxxCodeAnd the xxx type is exactly the parameter type of the AAA Single-parameter constructor,
At this time, the compiler automatically calls this constructor to create an AAA object. It looks cool and convenient.
However, in some cases (see the following authoritative example (ProgramMember. It's a success or a failure.
In this case, we need to add the explicit it modifier before the constructor, specifying that the constructor can only be called explicitly, used, and cannot be implicitly used as a type conversion operator.
Haha, it seems better to be bright. Functions of the explicit Constructor
Resolution: The explicit constructor is used to prevent implicit conversion. See the following code:
1 class test1
2 {
3 public:
4 test1 (int n) {num = N;} // common Constructor
5 private:
6 int num;
7 };
8
9 class Test2
10 {
11 public:
12 explicit Test2 (int n) {num = n ;}// explicit (explicit) constructor
13 private:
14 int num;
15 };
16
17 int main ()
18 {
19 test1 T1 = 12; // call its constructor implicitly. The constructor is successfully called.
20 Test2 t2 = 12; // compilation error. Its constructor cannot be called implicitly.
21 Test2 T3 (12); // display that the call is successful
22 return 0;
23}
The constructor of test1 contains an int type parameter. Code 19 is implicitly converted to the constructor called test1.
The constructor of Test2 is declared as explicit, which means that this constructor cannot be called through implicit conversion. Therefore, Code 20 may encounter a compilation error.
A common constructor can be called implicitly. While the explicit constructor can only be displayed and called.