从字符串文字到unsigned int(bool)的Imcplicit转换

时间:2018-03-26 11:14:50

标签: c++ implicit-conversion

当我运行下面的测试程序时,我原本希望字符串文字匹配std::string构造函数,而不是调用bool版本。我想知道标准中是如何涵盖的,我当然不明白为什么会将其转换为bool。 当我将bool替换为[unsigned] int时,它会按预期工作。

#include <iostream>
#include <string>

class Test
{
public:
    Test(bool value)
    {
        std::cout << "BOOL constructor: " << value << std::endl;
    }

    Test(std::string value)
    {
        std::cout << "string constructor: " << value << std::endl;
    }
};


int main()
{
    Test t0(true);
    Test t1(false);
    Test t2(2);
    Test t3("TEST1");

    std::string ts = "string";
    Test t4(ts);
}

输出bool:

BOOL constructor: 1 BOOL constructor: 0 BOOL constructor: 1 BOOL constructor: 1 string constructor: string

输出int:

BOOL constructor: 1 BOOL constructor: 0 BOOL constructor: 2 string constructor: TEST1 string constructor: string

0 个答案:

没有答案