C++ Primer implicit type conversion learning arrangement

  • 2020-07-21 09:31:58
  • OfStack

C++ Primer has the following statement: a constructor that can be called with a single argument defines a transformation from a parameter type to that type. This sentence is represented by the following code:


class A
{
  A(B b);// A constructor for a single argument 
  func(A a);
} 
.....
A a ; 
B b;
a.func(b);//func The function should have accepted A Argument of type, but due to the existence of a special constructor, so B Parameter of type b With the help of this special constructor A Type object to complete the transformation. So this statement is correct 

As you can see from the code snippet above, a constructor called with a single argument defines a transformation from a class type to another type, and this transformation occurs implicitly. Here are a few keywords: single argument, constructor, implicit transformation.

What happens during an implicit conversion? Object a does not have a member function of argument type B, but it has a constructor with a single 1B class parameter, so no errors are reported at compile time. For the statement a. func(b), the compiler USES this special constructor to generate a temporary object, then calls the regular func (A a) function as a temporary object, the func (A a) function ends, and the temporary object is logged off.

Is this conversion good or not? It varies from class to class, from context to context! There are times when you need it and times when you don't want it, and the language has this feature by default. However, you can also block this invisible "optimization" with the keyword explicit! The explicit keyword can only be used with constructors and is only annotated when a function is declared, not when a class function is defined.

In the above example, if you prevent implicit type conversion with the constructor A (B b), you can do the following for the constructor declaration:


explicit A (B b)

The statement a. func(b) would be an error, but we can explicitly use the constructor, as in the above example, and we can use the statement


a.func(A(b))

Do the same thing without implicit conversion. A (b) generates temporary A objects and passes them to function func calls, 1 following the rules without any implicit, programmer's invisible steps. The constructor shown disables the implicit use of constructors, and any constructor can explicitly create a temporary object, which is its right, even constructors modified by explicit.

As for implicit class type conversions, the authors of C++ Primer have this to say: In general, unless there is an obvious reason to define implicit conversions, the simplex parameter constructor should be explicit. Setting the constructor to explicit avoids errors and allows the user to explicitly construct the object when the transformation is useful.


Related articles: