简体   繁体   English

将初始化列表传递给基于向量的构造函数

[英]Passing an initializer list to a vector based constructor

I currently have the following code 我目前有以下代码

class test
{
   public:
   test(std::vector<std::string> str)
   {
   }
   test()
   {
   }
    const std::multimap<int,  std::multimap<int, test>> _var= {
                 {0x01,  {
                            {
                                0x0f, {"A", "B", "C", "D"}
                            }
                         }
                 }
        };   
};

int main()
{  
  test t;
}

Error: 错误:

main.cpp:29:9: error: could not convert '{{1, {{15, {"A", "B", "C", "D"}}}}}' from '<brace-enclosed initializer list>' to 'const std::multimap<int, std::multimap<int, test> >'
         };
         ^

I wanted to know why passing {"A", "B", "C", "D"} to std::vector<std::string> str) is failing ? 我想知道为什么将{“A”,“B”,“C”,“D”}传递给std::vector<std::string> str)失败了? Any suggestions on how I can resolve this issue ? 有关如何解决此问题的任何建议?

You need another pair of braces. 你需要另一对牙套。 Use: 采用:

0x0f, {{"A", "B", "C", "D"}}

Without that, the compiler tries to construct a test using the arguments "A", "B", "C", "D" , as if test{"A", "B", "C", "D"} , which does not work. 如果没有这个,编译器会尝试使用参数"A", "B", "C", "D"构建test ,就好像test{"A", "B", "C", "D"} ,这不起作用。

This will work: 这将有效:

class test
{
   public:
   test(std::vector<std::string> str)
   {
   }
   test()
   {
   }
    const std::multimap<int,  std::multimap<int, test>> _var= {
                 {0x01,  {
                            {
                                0x0f, std::vector<std::string>{"A", "B", "C", "D"}
                            }
                         }
                 }
        };   
};

Nevertheless, you should never pass containers by value. 但是,您永远不应该按值传递容器。

An alternative approach is to use an std::initializer_list in your ctor, then your code can be written as: 另一种方法是在你的ctor中使用std :: initializer_list,然后你的代码可以写成:

class test
{
   public:
   test(std::initializer_list<std::string> str)
   {
   }
   test()
   {
   }
    const std::multimap<int,  std::multimap<int, test>> _var= {
                 {0x01,  {
                            {
                                0x0f, {"A", "B", "C", "D"}
                            }
                         }
                 }
        };   
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM