是否可以在C ++中的成员初始化列表中初始化数组?

时间:2015-11-30 04:15:40

标签: c++ arrays member initializer-list

所以,我有这个Game类,我有一个SDL_Rect数组。如果可能的话,我想在成员初始化列表中初始化它,而不是在构造函数体内初始化数组。

//Game.h
#pragma once

class Game {
public:
  Game(SDL_Window* window, SDL_Renderer* renderer);

private:
  SDL_Rect down[4];
};

// Game.cpp
#include "Game.h"

Game::Game(SDL_Window* window, SDL_Renderer* renderer){
  down[0] = {1,4,31,48};
  down[1] = {35,5,25,47};
  down[2] = {65,4,31,48};
  down[3] = {100,5,26,47};
}

我想做这样的事情:

// Game.cpp
Game::Game()
: down[0]({1,4,31,48};
  // etc, etc...
{}

2 个答案:

答案 0 :(得分:3)

您可以将direct-list-initialization(因为c ++ 11)用于成员变量。 (不是数组的元素之一。)

Game::Game()
: down {{1,4,31,48}, {35,5,25,47}, {65,4,31,48}, {100,5,26,47}}
{}

LIVE

答案 1 :(得分:2)

没有问题。

所以这是一个令人困惑的问题。

struct Rect { int x, y, width, height; };

struct Game
{
    Rect down[4] =
    {
        {1,4,31,48},
        {35,5,25,47},
        {65,4,31,48},
        {100,5,26,47},
    };
};

#include <iostream>
using namespace std;
auto main() -> int
{
    Game g;
    for( Rect const& rect : g.down )
    {
        cout << rect.x << ' ';
    }
    cout << endl;
}

为了使用std::array代替原始数组(通常是Good Idea™)并使用g ++编译代码,请在初始化程序中添加一组内部括号,如下所示:

std::array<Rect, 4> down =
{{
    {1,4,31,48},
    {35,5,25,47},
    {65,4,31,48},
    {100,5,26,47}
}};

将初始化放置在构造函数的成员初始化列表中(如果由于某种原因需要,而不是上面的内容)可以如下所示:

#include <array>

struct Rect { int x, y, width, height; };

struct Game
{
    std::array<Rect, 4> down;

    Game()
        : down{{
            {1,4,31,48},
            {35,5,25,47},
            {65,4,31,48},
            {100,5,26,47}
        }}
    {}
};

#include <iostream>
using namespace std;
auto main() -> int
{
    Game g;
    for( Rect const& rect : g.down )
    {
        cout << rect.x << ' ';
    }
    cout << endl;
}