繁体   English   中英

在C ++中,有没有更有效的方式来编写多个声明

[英]In C++, is there a more efficient way to write multiple declarations

在C ++中,有没有更有效的编写方式:

ImageButton* imageButton;
ImageButton* imageButton1;
ImageButton* imageButton2;
ImageButton* imageButton3;

等没有写出所有的行? 我有1000多个按钮。 我希望有一种更好的方法来编写此代码。

谢谢

如果您坚持使用多个变量,请像这样一行地进行操作。

ImageButton *imageButton, *imageButton1, *imageButton2 ;

您也可以通过一种方法消除星星,但是这种方法几乎比您更差或更优。 如果使用一系列对象,IT会更好。

ImageButton [] ;

或动态的(如果您希望以后扩展)。

ImageButton * imagebutton = new ImageButton [size] ;

您必须这样做:

ImageButton *imageButton, *imageButton1, *imageButton2, *imageButton3;

换句话说,必须为每个变量单独显示* 或者您可以这样做:

typedef ImageButton* ImageButtonPtr ;
ImageButtonPtr imageButton, imageButton1, imageButton2, imageButton3;
nButtons = 1000
std::vector<ImageButton> images;
images.assign(nButtons, ImageButton())

这算什么

#include<iostream>
using namespace std;

class ImageButton
{

};



int main()
{


    int i;
    int BUTTONSIZE=32*32;    // 32x32 pixels
    int BUTTONAMOUNT=1000;     // 1000 buttons


    ImageButton **imagebutton = 0;

    //memory allocated for 1000 elements , BUTTONAMOUNT=1000
    imagebutton = new ImageButton *[BUTTONAMOUNT] ;


    //memory allocated for  elements of each button.
    for(   i = 0 ; i < BUTTONAMOUNT ; i++ ) 
    {
        imagebutton[i] = new ImageButton[BUTTONSIZE];
        cout<<i<<".  \n";
    }


    //free the allocated memory
    for(   i = 0 ; i < BUTTONAMOUNT ; i++ )     delete [] imagebutton[i] ;
    delete [] imagebutton ;

    return 0;
}

暂无
暂无

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

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