C++错误的构造函数被调用

use*_*138 9 c++ c++11

我希望下面的代码可以打印Test::Test(string,string,bool),但是会打印出来Test::Test(string,bool).为什么在提供两个字符串时只调用一个字符串参数的构造函数?当然一个字符串不能转换为bool ......?我尝试添加显式关键字,但它没有帮助.代码也在http://ideone.com/n3tep1.

#include <iostream>
#include <string>

using namespace std;

class Test
{
public:

    Test(const string& str1, bool flag=false)
    {
        cout << "Test::Test(string,bool)" << endl;
    }

    Test(const string& str1, const string& str2, bool flag=false)
    {
        cout << "Test::Test(string,string,bool)" << endl;
    }
};

int main()
{
    Test* test = new Test("foo", "bar");
}
Run Code Online (Sandbox Code Playgroud)

R S*_*ahu 6

用于构造的参数的类型Testchar const[4].

char const[4]衰变char const*,并且必须转换为a bool或a std::string const&使函数调用明确无误.

可以bool使用标准转换规则将指针转换为指针.

char const*可以std::string const&使用用户定义的转换规则将A 转换为.

鉴于此,从转换char const*,指针,以bool被认为比从转换更好的匹配char const*std::string const&.

因此,调用解析为第一个构造函数.


Som*_*ude 0

我希望编译器会抱怨不明确的函数。

我希望您调用错误的构造函数的原因是,使用字符串文字会产生指针,并且指针可以隐式转换为布尔值。

在这种情况下,编译器显然认为布尔转换比转换为std::string.