通过初始化列表初始化构造函数中的类成员(向量) [英] Initializing class member (vector) in constructor via initialization list

查看:136
本文介绍了通过初始化列表初始化构造函数中的类成员(向量)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11标准提供了使用这样的初始化列表初始化向量的机会。

The C++11 standard gives an opportunity to initialize a vector with an initialization list like this.

vector <int> a {3, 5, 6, 2};

我只是想知道是否可以初始化构造函数中类成员的向量通过初始化列表。

I am just wondering if it is possible to initialize a vector which is a member of class in a constructor via initialization list.

我寻找了这样的东西,但是我没有在Internet上或Stack Overflow上找到它,所以我认为我应该提出这一要求。我希望不仅我,而且其他人也会觉得它有用。

I looked for such a thing but I did not find it on the Internet or here on Stack Overflow, so I thought that I should ask for it. I hope that not only I, but also others will find it useful.

我不想使向量成为类的静态成员

该类应如下所示:

class Foo
{
    public:
        vector <int> myvector;
        //Here should be a constructor 
};

可以这样使用:

Foo aa{1, 2, 3, 6, 1}; // it should initialize a vector 


推荐答案

是!您只需要输入 std :: initializer_list 并使用它初始化向量。

Yes ! You just need to take in an std::initializer_list and initialize your vector with it.

struct Foo {
    Foo(std::initializer_list<int> l)
    : _vec{l} { }

    std::vector<int> _vec;
};

在Coliru上直播

这篇关于通过初始化列表初始化构造函数中的类成员(向量)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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