简体   繁体   English

如何添加到对象数组指针C ++

[英]How to add to object array pointer c++

I'm trying to add an object to an object array passed as an argument. 我试图将一个对象添加到作为参数传递的对象数组中。 Specifically, I have an array of buttons and I am adding a back button to the button array. 具体来说,我有一个按钮数组,并且正在向按钮数组添加一个后退按钮。 How can I correctly do this? 如何正确执行此操作? When I try the code below I get some weird glitches with the buttons passed from the original pointer array. 当我尝试下面的代码时,从原始指针数组传递的按钮会出现一些奇怪的故障。

int createMenu(Button buttons[], int size)
{
    //Stuff here
}

int menu(Button buttons[], int size, bool back)
{
    Button * newButtons[size + 1];
    for (int i = 1; i <= size; i++)
        *newButtons[i] = buttons[i];
    Button back(25, 19, "Back"); //Creates back button object
    *newButtons[0] = back;
    return createMenu(*newButtons, size + 1);
    //Makes menu with the back button
}

Any help is appreciated. 任何帮助表示赞赏。

In your loop you reference buttons[size], which is ouside of its bounds. 在循环中,您引用button [size],这是其边界的一部分。 You also dereference members of newButtons without initializing them. 您还可以取消引用newButton的成员而无需对其进行初始化。 And you try to pass createMenu an array of pointers, when it expects an array of buttons. 当您期望按钮数组时,尝试将createMenu传递给指针数组。 Should be something like this: 应该是这样的:

int menu(Button buttons[], int size, bool back)
{
    Button * newButtons = new Button[size + 1];
    for (int i = 0; i < size; i++)
        newButtons[i + 1] = buttons[i];
    newButtons[0] = Button(25, 19, "Back");
    int result = createMenu(newButtons, size + 1);
    delete [] newButtons;
    return result;
}

For reference, here's how it would look if you were using vectors: 作为参考,下面是使用向量时的外观:

int menu( std::vector<Button> buttons )
{
    buttons.push_back( Button(25, 19, "Back") );
    return createMenu( buttons );
}

If the button really needs to be pushed at the front then there are various options (eg actually push it at the front; or use a deque instead of a vector). 如果确实需要将按钮按在前面,则有多种选择(例如,实际上将其按在前面;或者使用双端队列代替矢量)。

Try this. 尝试这个。 You are using Button*, so pass address of the Button object. 您正在使用Button *,因此请传递Button对象的地址。

int menu(Button buttons[], int size, bool back)
{

    Button ** newButtons = new Button*[size + 1];
for (int i = 1; i <= size; i++)
        newButtons[i] = &buttons[i];
    Button * back = new Button(9,11,"fdf"); //Creates back button object
    newButtons[0] = back;

    //Makes menu with the back button
createMenu(*newButtons, size+1);
}

void createMenu(Button buttons[], int size)
{
    (buttons[0]).foo();

    //Stuff here
}

Also, you are using the same variable name "back" both as bool and as object of Button class. 另外,您正在使用相同的变量名“ back”作为bool和Button类的对象。 Change that. 改变它。

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

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