c++11/14新特性解读之二 explicit关键字

对于多个参数的明确的构造函数-在构造函数前加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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

华衣在盛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值