【发布时间】:2015-08-27 15:38:10
【问题描述】:
我希望下面的代码打印Test::Test(string,string,bool),但它打印Test::Test(string,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");
}
【问题讨论】:
-
"bar"不是std::string,它是const char*,并且指针可以隐式转换为bool,并且该转换必须优先于std::string( const char* )构造函数. -
第一个版本比较好,试试 new Test("foo", std::string("bar"))
-
在一些相关的说明中,您通常不希望在 C++ 代码中经常使用
new。如果可能,最好使用堆栈变量。只是提醒一下,因为你说你已经离开一段时间了。 -
谢谢。我正在使用 C++11,最近遇到的一些其他事情让我相信字符串文字被视为 std::string,但我猜它们只是被隐式转换并且没有竞争转换,例如ptr -> bool 一个我在这里打的。我避免使用新的,但在弄乱代码时添加了它。
-
我遇到了同样的问题,并通过将
bool更改为int/char解决了它,因为我真的不喜欢在调用中像@Melkon 那样记住写一个显式的字符串构造建议。