简体   繁体   中英

How do I define static array in .cpp file of my class

I know there is many question talks about static function and variable but I can't find the one that explain me how do things like this:

board.h

 class board:public QGraphicsPixmapItem 
{
public:
    board();
    static basedice *gamepos[8][8];
};

and I want to defined my array like this:

board.cpp

board::board()
{
    for (int i=0;i<8;i++)
    {
        for (int j=0;j<8;j++)
        {
        gamepos[i][j]=NULL;
        }
    }

}

And I have one more question,Is that a right way to use an array in many classes something like global array... for example in chess game for holding postion of my pieces? Sorry for my bad english.

If you really want the gamepos array to be static you can declare a static method in class Board that will initialize the array.

Then you call this method from outside the class.

int main() {

    Board * myboard = new Board();
    Board::initGamepos();

}

However looking at your code and what you want to do (which is reinitialize the gamepos array everytime you create a new Board instance, it is clear that you do NOT want gamepos to be static. 1 board <=> 1 gamepos array : that is not the mark of a static member, that is the mark of a standard member.

Static variables are automatically initialized to zero/false/null, so you don't need to initialize the array.

Anyway, you should not be reinitializing a static variable from your instance constructor as that will produce funny results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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