How to initialize an array that is a member of a class?

For example, I have a class called DeckOfCards and an array of char * suit [4].

class DeckOfCards
{
public:
    // some stuff

private:
    char *suit[ 4 ];
};

Where can I initialize this array this way? char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }I assume that this can be done using the constructor, but I don’t know how to do it exactly.

+3
source share
2 answers

You can create it as a static variable in a class, for example:

class DeckOfCards
{
public:
  DeckOfCards() {
    printf("%s\n", suit[0]);
  }

private:
  static const char *suit[];
};

const char *DeckOfCards::suit[] = { "Hearts", "Diamonds", "Clubs", "Spades" };

int main(void)
{
  DeckOfCards deck;
  return 0;
}
+5
source

Try the following:

DeckOfCards::DeckOfCards()
    :suit{ "Hearts", "Diamonds", "Clubs", "Spades" }
{}

If this does not work, your compiler does not yet support this C ++ function. So you need to do it the old way:

DeckOfCards::DeckOfCards()    
{
    suit[0] = "Hearts";
    suit[1] = "Diamonds";
    suit[2] = "Clubs";
    suit[3] = "Spades";
}

If you are going to use char pointers like this, you should make them const, i.e.:

const char *suit[ 4 ];

, . const, , , . std::string.

+5

All Articles