C ++ class explicit and implicit conversion conversion

Following constructor is used to convert the value of type double Stonewt type:

Stonewt(double lbs);

In other words, you can write code like this:

Stonewt myCat;
myCat = 19.6;

The constructor uses Stonewt (double) to create a temporary object, as the initial value and 19.6. Then, assign a member-by-way to copy the contents of the temporary object to myCat in. This process is called implicit conversion, because it is automatic, without the need for explicit cast.
Only accepts a parameter to the constructor as a conversion function. The following function has two parameters, and therefore can not be used to convert Type:

Stonewt(int stn, double lbs);

However, if a default value is provided to the second parameter, which can be used to convert int:

Stonewt(int stn, double lbs = 0);

Because of this automatic feature is not always desirable, C ++ new keyword explicit, for closing this automatic feature. For example, the following statement constructors:

explicit Stonewt(double lbs);

This turns off the implicit conversion, but then allows any explicit conversion, i.e., an explicit cast:

Stonewt myCat;
myCat = 19.6;   //not valid
mycat = Stone(19.6);  //OK, an explicit conversion

Note: Only constructor that takes one parameter defines the parameter type conversion from type to type. If the keyword explicit function defining this configuration, it can only be converted for display, or may be used for implicit conversion.

Guess you like

Origin www.cnblogs.com/ticonci/p/12455661.html