String literal matches bool overload instead of std::string(字符串文字匹配 bool 重载而不是 std::string)
问题描述
我正在尝试编写一个具有一些重载方法的 C++ 类:
I am trying to write a C++ class that has some overloaded methods:
class Output
{
public:
static void Print(bool value)
{
std::cout << value ? "True" : "False";
}
static void Print(std::string value)
{
std::cout << value;
}
};
现在假设我按如下方式调用该方法:
Now lets say I call the method as follows:
Output::Print("Hello World");
这是结果
是的
那么,为什么,当我定义了该方法可以接受布尔值和字符串时,当我传入一个非布尔值时,它是否使用布尔重载?
So, why, when I have defined that the method can accept boolean and string, does it use the boolean overload when I pass in a non-boolean value?
我来自 C#/Java 环境,对 C++ 很陌生!
推荐答案
"Hello World" 是一个类型为array of 12 const char"的字符串字面量,可以转换为指向 const char 的指针",然后又可以转换为 bool.这正是正在发生的事情.编译器更喜欢使用 std::string 的转换构造函数.
"Hello World" is a string literal of type "array of 12 const char" which can be converted to a "pointer to const char" which can in turn be converted to a bool. That's precisely what is happening. The compiler prefers this to using std::string's conversion constructor.
涉及转换构造函数的转换序列称为用户定义的转换序列.从 "Hello World" 到 bool 的转换是一个标准转换序列.标准规定标准转换序列始终优于用户定义的转换序列(第 13.3.3.2/2 节):
A conversion sequence involving a conversion constructor is known as a user-defined conversion sequence. The conversion from "Hello World" to a bool is a standard conversion sequence. The standard states that a standard conversion sequence is always better than a user-defined conversion sequence (§13.3.3.2/2):
标准转换序列 (13.3.3.1.1) 是比用户定义的转换序列或省略号转换序列更好的转换序列
a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence
这种更好的转换顺序"分析是针对每个可行函数的每个参数进行的(并且您只有一个参数),并且通过重载决议选择更好的函数.
This "better conversion sequence" analysis is done for each argument of each viable function (and you only have one argument) and the better function is chosen by overload resolution.
如果你想确保调用 std::string 版本,你需要给它一个 std::string:
If you want to make sure the std::string version is called, you need to give it an std::string:
Output::Print(std::string("Hello World"));
这篇关于字符串文字匹配 bool 重载而不是 std::string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:字符串文字匹配 bool 重载而不是 std::string
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
