I am working on a card game simulator and when I access a variable from an upper class the compiler shows an "undefined reference to" error. Does any know a solution?
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
class Game{
public:
static std::vector<int> usableDeck;
private:
class Player {
public:
void pickCard() {
usableDeck.push_back(0);
}
};
public:
void startGame() {
Player player;
player.pickCard();
}
};
int main() {
Game game{};
game.startGame();
return 0;
}
CodePudding user response:
Nested classes don't work the way you think. In particular, from Player
within Game
, you cannot access a member (e.g. usableDeck
) of Game
without an instance of Game
. To make it work, you might either pass an instance of Game
to pickCard()
or store a reference to Game&
in Player
.
CodePudding user response:
The
static vector<int> usableDeck;
is just a declaration. Initialize it outside the class definition with something like
std::vector<int> Game::usableDeck = {};