Application of C++ Explicit Constructor
This question already has an answer here:
An explicit constructor is a function that does not get called in implicit type conversion.
For example:
class A {
A( int a ) {}
};
void foo( A a ) {}
Here is totally legal to call foo(1)
or use any variable of type int or that can be implicitly converted to an int. This is not always desirable, as it would mean that A
is convertible from an integer, instead of being defined with an integer. Adding the explicit
would avoid the conversion and, hence, give you a compilation error.
A non-explicit one-argument constructor could be called a conversion constructor. That's because they allow the compiler to implicitly convert from another type (the type of the argument) to the object.
This implicit conversion is not always wanted, and can be disabled by marking the constructor explicit
.
上一篇: 显式和隐式构造函数
下一篇: C ++显式构造器的应用