小编Mic*_*hel的帖子

初始化列表作为operator []的参数

这个问题与这里讨论的问题有关.

我尝试使用初始化列表来创建要传递给的参数operator[].

#include <string>
#include <vector>

struct A {

std::string& operator[](std::vector<std::string> vec)
{
  return vec.front();
}

};

int main()
{
    // ok
    std::vector<std::string> vec {"hello", "world", "test"};

    A a;
    // error: could not convert '{"hello", "world", "test"}' to 'std::vector...'
    a[ {"hello", "world", "test"} ];
}
Run Code Online (Sandbox Code Playgroud)

我的编译器(GCC 4.6.1)抱怨:

g++ -std=c++0x test.cpp
test.cpp: In function ‘int main()’:
test.cpp:20:8: error: expected primary-expression before ‘{’ token
test.cpp:20:8: error: expected ‘]’ before ‘{’ token
test.cpp:20:8: error: expected ‘;’ before ‘{’ token …
Run Code Online (Sandbox Code Playgroud)

c++ curly-braces initializer-list c++11

6
推荐指数
1
解决办法
643
查看次数

标签 统计

c++ ×1

c++11 ×1

curly-braces ×1

initializer-list ×1