简体   繁体   中英

C++ - static objects/variables used across a project vs. using pointer/reference arguments

I'm writing a simple memory game (the one with the cards you flip) with C++ and SDL, and I'm finding it difficult to decide whether I'd use a class such as this:

class Game {
public:
   static StartMenu* sMenu;
   static OptionsMenu* oMenu;
   static GameBoard* board;

   static Card cards[36];
}

And then refer to them like this

Game::menu->selectedItem = 1;

Or should I just construct the project so that I'd instantiate the objects somewhere and then pass them to functions as pointers/references (I'll figure out which ones I should use later)? Like this

void processInput(SDL_Event event, StartMenu*&*& menu) {
    ...
    menu->selectedItem = 1;
    ...
}

Or is it just a matter of preference? The latter one seems "cleaner" but the former is more flexible...

I would recommend using:

class Game {
public:
   StartMenu* sMenu;
   OptionsMenu* oMenu;
   GameBoard* board;

   Card cards[36];
};

Create an instance of Game and pass it around.

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