Could not convert from '<brace-enclosed initializer list> to

我的未来我决定 提交于 2021-01-28 07:09:04

问题


I know that has a lot of questions similar, but I saw them and none of them helped me, I think is that because mine is kind of different, and at the same time weird.

I made another question and a member answered to me, but instead of using classes he used structs. and it's working perfectly, but when I try to put it as classes, using the same logic, this is what happen, the error:

error: could not convert '{{"foo", "bar"}}' from '' to 'B'

I tried, but I don't know what is happening.

#include <iostream>
#include <map>

class A
{
public:
    A() {}
    A(const std::string & input) : data(input) {}
private:
    std::string data;
};

class B
{
public:
    B();
    B(std::initializer_list<std::pair<std::string, A>> input) : container(begin(input), end(input)) {}
private:
    std::map<std::string, A> container;
};

int main( int argc, char ** argv )
{
    B b = {
        {"foo", "bar"}
    };

    return 0;
}

Also the answer of the member here: Ideone

Thank you all.


回答1:


You must initialize the 'b' like this:

B b = {
    { "foo", A{"bar"} }
};

Because {"foo", "bar"} is of type {string, string} instead of {string, A}



来源:https://stackoverflow.com/questions/21941967/could-not-convert-from-brace-enclosed-initializer-list-to

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!