C++11新特性之 explict

C++11新特性之 explict

目的

指定构造函数或转换函数为显示,即不能用于隐式转化;

语法

一般出现在类定义之内的构造函数中;
如:

class P
{
	explict P(){};
};

代码示例

#include <iostream>

class Test
{
public:
	Test(int a):a_(a)
	{
		std::cout << "Test()" << std::endl;  // 通过打印看调用几次构造函数
	}
	int Get_Data()
	{
		return a_;
	}
	Test operator + (Test t)
    {
        return Test(a_ + t.a_);
    }
private:
	int a_;

};

int main()
{
	Test t1{3};
	Test t2 = t1 + 5;   // 5 会隐式的调用的Test构造函数
	std::cout << t2.Get_Data() << std::endl;  //输出 8
}

在上一个的例子的基础之上加上 explict

#include <iostream>

class Test
{
public:
	explicit Test(int a):a_(a)
	{
		std::cout << "Test()" << std::endl;  // 通过打印看调用几次构造函数
	}
	int Get_Data()
	{
		return a_;
	}
	Test operator + (Test t)
    {
        return Test(a_ + t.a_);
    }
private:
	int a_;

};

int main()
{
	Test t1{3};
	Test t2 = t1 + 5;  //error   
	// error: no match for 'operator+' (operand types are 'Test' and 'int')
	//说明 5 还是个int类型, 不能隐式的转化为Test
	
}

explicit用于多个参数

#include <iostream>
struct P
{
	P(int a, int b)
	{
		std::cout << "P(int a, int b)" << std::endl;
	}

	explicit P(int a, int b, int c)
	{
		std::cout << "explicit P(int a, int b, int c)" << std::endl;
	}
};

int main()
{
	P p1(1,2);    //OK P(int a, int b)
	P p2{1,2};    //OK P(int a, int b)
	P p3 = {1,2}; //OK P(int a, int b)

	P p4(1,2,3);  //OK explicit P(int a, int b, int c)
	P p5{1,2,3};  //OK explicit P(int a, int b, int c)
	P p6 = {1,2,3}; //error:converting to 'P' from initializer list would use explicit constructor 'P::P(int, int, int)
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值