在C++中,构造函数可以用来做隐性的type conversion。比如:
#include <iostream>
using namespace std;
class A
{
public:
A();
A(int) {cout << "First constructor called" << endl;}
A(const char*, int = 0) {cout << "Second constructor called" << endl;}
};
int main() {
A a = 1;
A b = "asdfasdf";
}
上面这段代码是合法的。我们注意在第13和14行,我们隐性地把int类型和char*类型转换成了A类型。我我们之所以能够这么做的原因是,A中有两个constructor,它们的特点是它们都可以只传入一个parameter。这样的constructor会被编译器用来自动地隐性地做type conversion。如果我们不想让编译器这么做,我们就应该在constructor前面标明explicit,那么这样就可以避免编译器自动做这样的事:
class A {
public:
A();
explicit A(int) {cout << "First constructor called" << endl;}
explicit A(const char*, int = 0) {cout << "Second constructor called" << endl;}
};