【发布时间】:2017-04-05 23:48:54
【问题描述】:
在以下代码中,当我尝试将列表传递给构造函数时,编译器给了我一个错误:
#include <string>
#include <iostream>
#include <list>
class MyClass {
std::list<std::string> strings;
public:
void disp() {
for (auto &str : strings)
std::cout << str << std::endl;
}
MyClass(std::string const &str)
: strings({str}) {}
MyClass(std::list<std::string> const &strlist)
: strings(strlist) {}
};
int main ()
{
// Compiles well:
MyClass c1("azerty");
c1.disp();
// Compilation error, "call to constructor of 'MyClass' is ambiguous":
MyClass c2({"azerty", "qwerty"});
c2.disp();
return 0;
}
我尝试将explicit 添加到构造函数的声明中,但它并没有改变任何东西。
【问题讨论】:
-
MyClass c2({{"azerty"}, {"qwerty"}});? -
@WhozCraig:是的,它正在工作,但为什么我必须添加额外的大括号?有没有办法删除它们以提高可读性?
-
因为std::string's 9th constructor overload 有一个初始化列表。
-
@Gill 错误的构造函数。那个不匹配
标签: c++ constructor