重载的布尔/字符串歧义 [英] Overloaded Bool/String Ambiguity
问题描述
为什么C ++强制将我传入的字符串文字转换为布尔值而不是字符串?
Why is C++ casting the string literal I pass in as a bool rather than a string?
#include <iostream>
using namespace std;
class A
{
public:
A(string v)
{
cout << v;
}
A(bool v)
{
cout << v;
}
};
int main()
{
A("hello");
return 0;
}
输出:1
是因为编译器不够聪明,无法从char *跳转到字符串,而是仅仅假设bool是最接近指针的东西吗?我唯一的选择是制作一个显式的char *构造函数,该构造函数基本上与字符串构造函数完全相同吗?
Is it because the compiler isn't smart enough to make the jump from char * to string and rather just assumes that bool is the closest thing to a pointer? Is my only option to make an explicit char * constructor that basically does the exact same thing as the string constructor?
推荐答案
如果您拥有C ++ 11,则可以使用委托的构造函数:
If you have C++11 you can use a delegating constructor:
A(char const* s) : A(std::string(s)) { }
之所以选择布尔转换构造函数而不是std::string
的原因是因为从char const*
到bool
的转换是标准转换,而到std::string
的转换是用户定义的转换.标准转化的排名要高于用户定义的转化.
The reason the boolean converting-constructor is chosen over the one for std::string
is because the conversion from char const*
to bool
is a standard conversion while the one to std::string
is a user-defined conversion. Standard conversions have a greater rank than user-defined conversions.
这篇关于重载的布尔/字符串歧义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!