Mar*_*tyC 5 c++ visual-studio-2010 visual-c++
我正在使用Visual Studio 2012(但是使用VC++ 2010构建工具),并且我在类中定义了这两个重载函数(下面的签名),我稍后在另一个实例化第一个类的类中调用它(也在下面):
Defined in the class:
Node CreateNode(Node *parent,string name,string node_text,bool expects_node = true);
Node CreateNode(Node *parent,string name, string attribute, string value,bool expects_node = true)
Calling these functions in the macro:
Node axis1 = handler->CreateNode(&sparse,"axis","id","trigger_pt");
Run Code Online (Sandbox Code Playgroud)
当我进行函数调用时,它调用第一个函数,而不是第二个函数!所以它将第二个字符串视为布尔值!但是,当我向函数调用添加"true"时,它会按预期调用第二个函数.有谁能解释一下?谢谢!
字符串文字"trigger_pt"
的类型为"11的数组const char
".编译器认为最好将其转换bool
为将其转换为a std::string
.原因是因为转换为bool
仅使用标准转换(数组到指针然后指向bool),而转换为std::string
需要调用构造函数.标准转换序列始终被认为优于用户定义的转换序列(涉及转换构造函数).
比较隐式转换序列的基本形式(如13.3.3.1中所定义)
- 标准转换序列(13.3.3.1.1)是比用户定义的转换序列或省略号转换序列更好的转换序列,并且
- [...]
您可以强制它使用第二个重载,使该文字成为std::string
:
Node axis1 = handler->CreateNode(&sparse,"axis","id",std::string("trigger_pt"));
Run Code Online (Sandbox Code Playgroud)
另一个替代方案是提供另一个需要a的重载const char*
,这将优于bool
版本.这种过载可以简单地转发到std::string
过载.