无法从“<大括号括起来的初始化列表>到 [英] Could not convert from '<brace-enclosed initializer list> to

查看:69
本文介绍了无法从“<大括号括起来的初始化列表>到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多类似的问题,但我看到了它们,但没有一个对我有帮助,我想是因为我的问题有点不同,同时也很奇怪.

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:

错误:无法将 '{{"foo", "bar"}}' 从 '' 转换为 'B'

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;
}

这里也是会员的回答:Ideone

谢谢大家.

推荐答案

你必须像这样初始化 'b':

You must initialize the 'b' like this:

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

因为 {"foo", "bar"} 的类型是 {string, string} 而不是 {string, A}

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

这篇关于无法从“&lt;大括号括起来的初始化列表&gt;到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆