简体   繁体   English

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

[英]Is it possible to initialize an array in a member initializer list in C++?

So, I have this Game class, and I have an array of SDL_Rect s.所以,我有这个Game类,我有一个SDL_Rect数组。 I would like to initialize it in the member initializer list if that's possible, instead of initializing the array inside the constructor body.如果可能的话,我想在成员初始值设定项列表中对其进行初始化,而不是在构造函数体内初始化数组。

//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};
}

I would like to do something like this:我想做这样的事情:

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

You could use direct-list-initialization (since c++11) for the member variable.您可以对成员变量使用 直接列表初始化(c++11 起)。 (Not every element of the array.) (并非数组的每个元素。)

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

LIVE居住

There is no problem.没有问题。

So it's a baffling question.所以这是一个令人困惑的问题。

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;
}

In order to use a std::array instead of the raw array, which is generally a Good Idea™, and have the code compile with g++, add an inner set of braces to the initializer, like this:为了使用std::array而不是原始数组(这通常是一个好主意™),并使用 g++ 编译代码,请向初始值设定项添加一组内部大括号,如下所示:

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

Placing the initialization in a constructor's member initializer list (if for some reason that's desired, instead of the above) can then look like this:将初始化放在构造函数的成员初始化列表中(如果出于某种原因需要,而不是上面的),则可以如下所示:

#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;
}

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

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