简体   繁体   English

初始化列表的简单示例

[英]Simple example of an initializer list

I'm looking for a simple example of how to use the initializer list. 我正在寻找一个如何使用初始化列表的简单示例。 Here's what I want to do: I've got the following class: 这就是我想要做的:我有以下课程:

class foo{
    public:
        void set_x(const int ix);
        void set_y(const int iy);
        void display();
    private:
        int x;
        int y;
};

I'd like to create an object of this class in the following way: 我想以下列方式创建此类的对象:

foo fooObj = {1, 2};

I know that it is possible with vector in C++11. 我知道在C ++ 11中使用vector是可能的。 How can I implement this kind of behaviour? 我该如何实现这种行为?

In this case, a simple constructor will work: 在这种情况下,一个简单的构造函数将工作:

foo(int x, int y) : x(x), y(y) {}

If the class were an even simpler aggregate (which yours would be if the data members were public) then you wouldn't even need that - this style of initialisation will initialise each member of an aggregate in turn. 如果这个类是一个更简单的聚合 (如果数据成员是公共的那么你的那个)那么你甚至不需要 - 这种初始化方式将依次初始化聚合的每个成员。

For something more complicated, like vector , where the number of arguments can vary, you need to use an initializer_list . 对于更复杂的东西,比如vector ,参数的数量可以变化,你需要使用initializer_list Include the header: 包括标题:

#include <initializer_list>

and a constructor 和一个构造函数

foo(std::initializer_list<int>);

The type acts like a container, with begin() , end() and size() functions to access its contents. 该类型的行为类似于容器,使用begin()end()size()函数来访问其内容。

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

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