[英]In C++, is there a more efficient way to write multiple declarations
In C++, is there a more efficient way to write: 在C ++中,有没有更有效的编写方式:
ImageButton* imageButton;
ImageButton* imageButton1;
ImageButton* imageButton2;
ImageButton* imageButton3;
etc without writing out all the lines? 等没有写出所有的行? I have over 1000 buttons. 我有1000多个按钮。 I was hoping there is a better way to write this. 我希望有一种更好的方法来编写此代码。
Thanks 谢谢
If you insist to use a number of variables, do it like this in a line. 如果您坚持使用多个变量,请像这样一行地进行操作。
ImageButton *imageButton, *imageButton1, *imageButton2 ;
You can eliminate the stars by a method as well but still this method is almost as worse or better than your. 您也可以通过一种方法消除星星,但是这种方法几乎比您更差或更优。 IT would be better if you use an array of objects. 如果使用一系列对象,IT会更好。
ImageButton [] ;
or a dynamic one if you like to grow it afterwards. 或动态的(如果您希望以后扩展)。
ImageButton * imagebutton = new ImageButton [size] ;
You have to do it like this: 您必须这样做:
ImageButton *imageButton, *imageButton1, *imageButton2, *imageButton3;
In other words, the *
has to be present for each variable separately. 换句话说,必须为每个变量单独显示*
。 Or you could do it like this: 或者您可以这样做:
typedef ImageButton* ImageButtonPtr ;
ImageButtonPtr imageButton, imageButton1, imageButton2, imageButton3;
nButtons = 1000
std::vector<ImageButton> images;
images.assign(nButtons, ImageButton())
What of this ? 这算什么 : :
#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.