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

标签 c++ arrays memory

我有以下内容:

Action* actions[];

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

本来我在做:

Action* actions[ 2 ];

然后在构造函数中:

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

执行此操作的最佳方法是什么?所以最后我可以在我的游戏循环中做一些类似

的事情
SomeFunctionIPassAnActionInto( actionBar->actions[ 0 ] );

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

Actions* actions [ 5 ]; 

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

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

有点东西

最佳答案

在 C++11 中,您可以在 ctor-initializer 中初始化数组。

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

{
}

关于C++ 我知道数组长度,但想知道是否有一种更简洁的方法来定义数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15939005/

相关文章:

c++ - 使用迭代器从 vector 中查找子字符串

c - 在动态数组上使用 strcpy

java - 有更好的方法吗?我想从一个数组中将字符减去到另一个数组中

c - 在执行后续代码之前强制执行内存写入

c++ - 如何判断驱动器是否在没有管理员权限的情况下被 BitLocker 加密?

c++ - VS2012中Linker和Librarian的区别

c++ - etags如何处理多个目录

c - 错误 : subscripted value is neither array nor pointer nor vector on boolean array

c++ - 如何从内存中删除动态添加的节点?

function - Julia 函数中的内存分配