C++ 我知道数组长度,但想知道是否是一种更简洁的数组元素定义方法

C++ I know the array length but was wondering if a cleaner way of defining the array elements

本文关键字:一种 简洁 方法 定义 数组元素 数组 我知道 是否是 想知道 C++      更新时间:2023-10-16

>我有以下内容:

Action* actions[];

在操作栏类中。

我想在其构造函数中做这样的事情:

actions = {
    new Action( new Image( gfx, "Images/ActionBar/Push001.png", 200, 200, TRUE ), 0, 200, 200, 200, 200 ),      
    new Action( new Image( gfx, "Images/ActionBar/Pull001.png", 200, 200, TRUE ), 1, 200, 200, 200, 200 )
};

最初我在做:

Action* actions[ 2 ];

然后在构造函数中:

actions[ 0 ] = new Action( new Image( gfx, "Images.....    
actions[ 1 ] = new Action( new Image( gfx, "Images.....
最好的

方法是什么?这样最后我就可以在我的游戏循环中做一些类似的事情

SomeFunctionIPassAnActionInto( actionBar->actions[ 0 ] );

编辑::稍微改变了问题,我总是知道会有5个动作,所以如果我这样做了

Actions* actions [ 5 ]; 

我将如何像这样声明数组元素:

actions = {
   new Action( "push" ),
   new Action( "pull" ),       
   new Action( "bla" ),
   new Action( "ble" ),       
   new Action( "blo" )
}

那种事情

在 C++11 中,您可以在 ctor 初始值设定项中初始化数组。

ActionBar::ActionBar()
    : actions {
        new Action( new Image( gfx, "Images/ActionBar/Push001.png", 200, 200, TRUE ), 0, 200, 200, 200, 200 ),      
        new Action( new Image( gfx, "Images/ActionBar/Pull001.png", 200, 200, TRUE ), 1, 200, 200, 200, 200 )
      }
{
}
How would I declare the array elements like this:
actions = {
   new Action( "push" ),
   new Action( "pull" ),       
   new Action( "bla" ),
   new Action( "ble" ),       
   new Action( "blo" )
}

使其工作的最简单方法是为 Action 定义一个构造函数,该构造函数采用 char const*char const* const*std::string const& 中的一个,然后将此参数(可能使用您展示的示例的某种翻译(转发到 Image 构造函数(由于 image 是成员,您需要在初始值设定项列表中执行一些操作,例如 _image(new Image(translate(arg))) 其中translate是您定义的函数,用于转动 pushImages/ActionBar/Push001.png(。

相关文章: