C++中explicit

之前在项目代码中看到explicit这个关键字,不知道什么意思。

C++ constructors that have just one parameter automatically perform implicit type conversion. For example, if you pass an int when the constructor expects a string pointer parameter, the compiler will add the code it must have to convert the int to a string pointer. However, you might not always want this automatic behavior.

大意是构造函数会隐式转换。

You can add explicit to the constructor declaration to prevent implicit conversions. This forces the code to either use a parameter of the correct type, or cast the parameter to the correct type. That is, if the cast is not visibly expressed in code, an error will result.

The explicit keyword can only be applied to in-class constructor declarations to explicitly construct an object.

如果添加explicit就会避免隐式转换。

上述来自MSDN。

比如:

#include<iostream>
#include <string>

class Things
{
public:
	Things(const std::string &name):
	  m_Name(name){}
	  std::string GetThings()const{return m_Name;}
private:
	  std::string m_Name;

};

int main()
{
	Things lTest = "Test";
	std::cout << lTest.GetThings() << std::endl;
}

这样是可以正常输出的。

但是一旦在构造函数签名加了explicit:

#include<iostream>
#include <string>

class Things
{
public:
	explicit Things(const std::string &name):
	  m_Name(name){}
	  std::string GetThings()const{return m_Name;}
private:
	  std::string m_Name;

};

int main()
{
	Things lTest = "Test";
	std::cout << lTest.GetThings() << std::endl;
}

就会出现error C2440: “初始化”: 无法从“const char [5]”转换为“Things”

嗯,木有办法隐式转换了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值