Use of C ++ keyword explicit

The first is the definition:
Explicit keywords can modify only one parameter constructor , or there are a number of parameters, but in addition to the first argument the other parameters have a default constructor values. Its role is to show that the constructor is explicitly shown. (Class constructor implicit default)

If the class constructor parameter is greater than or equal to two, an implicit conversion is not generated, it is also invalid keyword explicit

for example:

class AMD{
public:
    AMD(int level){  //这里的构造函数默认就是隐式声明
        .....
        }
.....
}

In this case, if you run the following statement:

AMD a(3);
AMD b=10;

These two are no problem, the second sentence AMD b = 10; there is no reason for the problem is:
C ++, the constructor if only one argument, then there will be a default conversion operation at compile time: the constructor a corresponding data type is converted to the class object.
That is AMD b = 10 in the actual implementation the operation equivalent to the following statement:

AMD b(10);
//或者
AMD c(10);
AMD b = c;

Although the explanation through, but such an approach is still unfriendly, after all, AMD b = 10 The wording looks like the integer assigned to the object, it is neither fish nor fowl, but in a complex code easy to feel confused - > so now we are going to use the explicit keyword

After explicit modification:

class AMD{
public:
    explicit AMD(int level){  //修饰后构造函数就是显式声明
        .....
        }
.....
}

In this case, two statements that go before execution,
the AMD A (. 3); still no problem, but AMD b = 10 is no longer feasible (explicit prevented implicit automatic conversion class constructor)
Use of C ++ keyword explicit
(case compiled an error occurs)

In accordance with the definition of explicit keywords, you can modify a number of parameters (of which only one has no default value) constructor:

class AMD{
public:
    explicit AMD(int level,int size=0....){  //除了第一个参数都有缺省值
        .....
        }
.....
}

In this case the keywords are explicit functions using AMD b = 10, etc. will produce implicit type conversions statement still being given.

Because modified with explicit type conversion constructor avoid unexpected, and no disadvantages, so under normal circumstances or encourage the use of explicit

Guess you like

Origin blog.51cto.com/14232799/2483022