对于多个参数的明确的构造函数-在构造函数前加explicit关键字
首先举例说明explicit关键字的用法:
未加explict:
struct Complex
{
int real, ima;
Complex(int re,int im=0):real(re),ima(im)
{
cout << "re=" << real << " ima=" << ima << endl;
}
Complex operator + (const Complex& x)
{
return Complex((real + x.real), (ima + x.ima));
}
};
int main()
{
Complex c1(12, 5);
Complex c2 = c1 + 5;
}
输出结果:
re=12 ima=5
re=5 ima=0
re=17 ima=5
在Complex c2 = c1 + 5;中,编译器使用隐式的构造函数,将5隐式转换为Complex(5,0)这样的对象。
加上explicit
struct Complex
{
int real, ima;
explicit Complex(int re,int im=0):real(re),ima(im)
{
cout << "re=" << real << " ima=" << ima << endl;
}
Complex operator + (const Complex& x)
{
return Complex((real + x.real), (ima + x.ima));
}
int main()
{
Complex c1(12, 5);
Complex c2 = c1 + 5;//编译器报错,错误 C2512 “Complex”: 没有合适的默认构造函数可用
};
编译器报错是因为构造函数使用了explicit关键字使得构造函数只能显式的调用,编译器不能做隐式的转换。
c++11之前没有explicit关键字的话,只满足构造函数单一实参,可以隐式转换,c++11之后可以没有explict关键字的话,有多个参数的构造函数,可以多个参数的隐式转换
如:
class P
{
public:
P(int a, int b)
{
cout << "P(int a,int b)" << endl;
}
explicit P(initializer_list<int>)
{
cout << "P(initializer_list<int>)" << endl;
}
explicit P(int a, int b, int c)
{
cout << "explicit P(int a, int b, int c)" << endl;
}
};
int main()
{
P p{ 1,2 };
P p2 = { 1,2,3 };//编译报错,因为只能显式调用,若explicit P(initializer_list<int>)去掉explicit,则编译成功,可以隐式调用
P P3(1, 2, 3);
return 0;
}