首页 > 解决方案 > 奇怪的构造函数行为

问题描述

我正在使用 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

编译器逻辑的一些背景是什么?

标签: c++initializationinitializer-list

解决方案


现在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像上面解释的那样隐式转换为。


推荐阅读