在 C++ 中如果一个构造函数只有一个参数,那么这个构造函数就是转换构造函数(Converting Constructor),这个构造函数可以将参数类型转换成构造函数所在的类对应的类型。
举个例子,假设有如下类 Complex:
1 class Complex {
2 private:
3 int i;
4 int j;
5
6 public:
7 // 1. 普通构造函数
8 Complex(int i, int j) {
9 this->i = i;
10 this->j = j;
11 }
12
13 // 2. 转换构造函数
14 Complex(int i) {
15 this->i = i;
16 this->j = 0;
17 }
18 };
上面代码注释2处就定义了一个转换构造函数,它可以将一个整数类型,转换成一个 Complex 类型。
假如有下面的调用:
// 此时会调用转换构造函数 Complex(5)
Complex c = 5;
那么转换构造函数就会被调用,将整数5转换成 Complex 类型,实际上等价于:
Complex c= Complex(5);
禁用隐式类型转换
上面的转换是编译器自动转换,称为隐式类型转换。如果不需要这种隐式类型转换,只需要在转换构造函数前面添加 explicit 关键字,如下所示:
// 2. 转换构造函数
explicit Complex(int i) {
this->i = i;
this->j = 0;
}
假如 explicit 之后,如果还进行如下调用编译器就会报错:
Complex c = 5; // 此时会报错
如果需要,仍然可以手动进行调用:
Complex c = Complex(5);