现在的位置: 首页 > 综合 > 正文

C++中explicit

2013年10月21日 ⁄ 综合 ⁄ 共 1258字 ⁄ 字号 评论关闭

之前在项目代码中看到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”

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

抱歉!评论已关闭.