c++ - 奇怪的构造函数行为
问题描述
我正在使用 Visual Studio 2013,这就是我想要弄清楚的:
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
int x = 1;
bool y = true;
A(int _x, bool _y) : x(_x), y(_y)
{
cout << "Constructor #1" << endl;
}
A(std::initializer_list<int> init_list)
{
cout << "Constructor #2" << endl;
}
};
int main(int argc, char** argv)
{
A Aobj1(10, false);
A Aobj2(20, "false");
A Aobj3{30, false};
A Aobj4{40, "false"};
return 0;
}
输出是:
Constructor #1 Constructor #1 Constructor #2 Constructor #1
第一次调用构造函数 #1 很好
现在
Aobj2(int, string)
调用构造函数#1 的第二个构造很奇怪。编译器如何(int, bool)
使用字符串参数调用构造函数?“false”bool
甚至没有转换为 int。Aobj3
也可以。虽然initializer_list
是 int 类型,但编译器会因为大括号初始化而调用它,并将 bool 转换为 int。这又让我感到困惑。我原以为这是一个错误,因为字符串无法转换为 int(就像使用 bool 一样),并且还期望编译器调用
initializer_list
构造函数,因为它是一个大括号初始化。但是编译器选择 (int, bool) 构造函数。
编译器逻辑的一些背景是什么?
解决方案
现在
Aobj2(int, string)
调用构造函数#1 的第二个构造很奇怪。编译器如何(int, bool)
使用字符串参数调用构造函数?
更准确地说,"false"
是类型const char[6]
并且可以衰减为const char*
,即指针,然后可以隐式转换为bool
。
整型、浮点、无范围枚举、指针和指向成员的指针类型的纯右值可以转换为 类型的纯右值
bool
。零值(对于整数、浮点和无范围枚举)以及空指针和指向成员的空指针值变为
false
. 所有其他值变为true
。
对于第 4 种情况,参数std::initializer_list<int>
不能匹配参数40, "false"
,因为没有隐式转换转换指针到int
. 然后选择构造函数int, bool
,因为"false"
可以bool
像上面解释的那样隐式转换为。
推荐阅读
- c# - 对角射击子弹
- javascript - 使用事件修改 javascript 文件
- log4net - 如何使用 Log4net 在代码中禁用特定方法调用的日志记录
- python - 括号、引号等的 Ipython shell 自动补全
- php - 如何在 Firefox 移动端而不是原生应用上打开 Google Play 商店
- java - 如何从 Java 中的 Stream 中创建 2D(二维)数组?
- django - django擦除模型的重复值
- r - 从文本/句子中提取搭配
- c# - 在 DataTrigger 的 Setter 中绑定不起作用
- javascript - 如何登录并将数据发布到 Web 服务