1

I'm making a poker game and I have a class which contains a std::map to assign a value for every card on the poker deck referring to its name. I tried to put it as a component of another class as static member, since I have to assign a value every time a card is created, but for some reason when I try to access to it I get compiler error undefined symbol or duplicated symbol.

My partial solution have been declaring the class container as a global variable outside a class scope, but I know it's a bad practice , and if not there is anyway my doubt.

extern Baraja baraja;

For some reason when I declare this as static member or static const member, happens that I cannot access to the values of the std::map or I get compiler error undefined symbol or duplicated symbol so as I have searched in web documentations and cannot find a reason or solution I have this question.

How to correctly create, initialize and access to a static member of a class?

Ibrahim CS
  • 119
  • 2
  • 9

1 Answers1

3

I think this is duplicated.

#include <string>
#include <unordered_map>

enum class CardColor {Heart};

struct Card
{
    CardColor color;
    int value;
};

class Game
{
private:
    static std::unordered_map<std::string, Card> deck;
public:
    Game(){}
};

In your .cpp file

std::unordered_map<std::string, Card> Game::deck = std::unordered_map<std::string, Card>
{
    std::pair<std::string,Card>{"HeartSeven",{ CardColor::Heart,7}},
    std::pair<std::string,Card>{"HeartEight",{ CardColor::Heart,8}}
};
StephanH
  • 463
  • 4
  • 12
  • Thank you very much! Is there a document or book you can reccomend to know this better? – Ibrahim CS Feb 04 '19 at 03:20
  • 1
    @IbrahimCS [this article](https://en.cppreference.com/w/cpp/language/static) provides a relatively technical description of what you've encountered. If you're looking for a more guided explanation, searching for 'static data member initialization' (i.e. what this answer demonstrates) will yield many more examples. – Richard Feb 04 '19 at 15:18