c++ - list<string> 和 string 之间的构造函数不明确

标签 c++ constructor

在下面的代码中,当我尝试将列表传递给构造函数时,编译器给我一个错误:

#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 添加到构造函数的声明中,但它并没有改变任何东西。

最佳答案

问题是 string 有这个构造函数:

template< class InputIt >
basic_string( InputIt first, InputIt last, 
              const Allocator& alloc = Allocator() );

which {"azerty", "qwerty"} 是一个不幸的匹配,因为 const char* 实际上是一个输入迭代器......即使两个参数不是迭代器,也不是同一容器中的迭代器。

一个解决方案是只提供一个构造函数,它接受一个初始化列表并只使用那个:

MyClass(std::initializer_list<std::string> il)
    : strings(il.begin(), il.end())
{ }

关于c++ - list<string> 和 string 之间的构造函数不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40262087/

相关文章:

Java - super 调用问题

c++ - 从 const string 到 bool 的隐式转换

c# - 我在哪里可以找到简单的 beta cdf 实现

c++ - 'cin'和 'getline'问题的真正解决方案

c++ - 为什么多次递增/递减在 C++ 中有效但在 C 中无效?

c++ - 将类构造函数作为方法调用

c++ - 矮人调试信息缺少构造函数上的数据

javascript - 参数列表周围带有花括号的类构造函数/函数语法

c++ - 为什么 fseek 不起作用?

c++ - 此代码如何在不重载赋值运算符的情况下运行