c++ - 如何初始化 const std::vector<MyClass>

标签 c++ constants stdvector initializer-list

我有一个像这样的容器类

class Container {
  public:
    Container(const std::string name, const double value)
        : name(name), value(value),{};
    const std::string name;
    const double value;
};

我喜欢初始化 const std::vector<Container>

这个

const std::vector<Container> sets{{"foo", 0}, {"bar", 1}};

使用 intel 编译器(版本 15.0.3(gcc 版本 4.8.2 兼容性))和 c++11 启用( -std=c++11 )可以正常工作,这适用于 RedHat6,但在 Windows7 下失败。编译器完全相同,但前端是 Visual Studio 2013。

我收到错误消息:

 no operator "=" matches these operands
           operand types are: Container = Container
           _Right = _Move(_Tmp);

我需要编写自己的复制构造函数吗?

完整的例子是

#include <vector>
#include <string>

class Container {
  public:
    Container(const std::string name, const double value) : name(name), value(value){};
    const std::string name;
    const double value;
};

int main() {
    const std::vector<Container> sets{{"foo", 0.0},{"bar", 1.0}};
}

最佳答案

我尝试用 VS2015 编译你的代码,它编译得很好。

我认为您只是遇到了编译器错误。我建议将您的 C++ 编译器升级到具有更好的现代 C++ 支持的新版本。

附注请注意,VS2015 也支持 Windows 7。

关于c++ - 如何初始化 const std::vector<MyClass>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50216426/

相关文章:

c# - 如何创建包含 const 内容的 C# 列表?

c++ - 连接两个 std::vectors

c++ - 删除元组成员的复制构造函数导致错误

c++ - Mat 和 setMouseCallback 函数

c++ - 我可以在 C++ 运行时初始化静态 const 成员吗?

c++ - std::vector::resize() 与 gcc 4.7.0 的奇怪行为

c++ - vector中包含的对象有什么要求

c++ - 如何在 C++ 和 Boost 中将数组参数传递给 TCP 客户端的函数

c++ - 现代 C++ 线程安全的 JSON?

c++ - 为了使函数返回编译时常量值,模板中是否需要 constexpr const Type?