First, constructor, default constructor, composition default constructor
Constructor , a special member function that has the same function name as the class name and no return type. You can have a list of initializations.
default constructor , no formal parameter, or constructor for all formal parameters with default arguments.
If no constructors are defined, the compiler automatically creates the default constructor for the composition . Even if a class defines only one constructor (whether it is a default constructor or not), the compiler will no longer generate a default constructor.
The composition's default constructor initializes members with the same rules as the variable initialization: Members with class types are initialized by running their respective default constructors, and members of built-in and composite types, such as pointers and arrays, are initialized only for objects defined in the global scope, and when the objects are defined in the local scope, Members of built-in and composite types are not initialized.
Ii. implicit class-type conversions
The constructor of a single parameter defines an implicit conversion from the formal parameter type to the class type.
So, how do you suppress implicit conversions defined by constructors?
Third, explicit (display) constructor
You can declare a constructor as explicit.
The explicit keyword can only be used on a constructor declaration inside a class, and it cannot be repeated on a function definition outside the definition body of the class.
In general, a single parameter constructor should be explicit unless there is a clear reason to define an implicit conversion. Setting the constructor to explicit avoids errors, and when the conversion is useful, the user can construct the object in a display.
Reference: C + + Primer Chinese version 4th edition P393
For classes that define only the explicit constructor, only direct initialization is used, and replication initialization cannot be used.
See C + + Primer Chinese version 4th edition P407
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Explicit constructor function