开发者

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

开发者 https://www.devze.com 2023-03-03 23:43 出处:网络
For example I have a class called DeckOfCards and array char *suit[ 4 ]. class DeckOfCards { public: // some stuff

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

class DeckOfCards
{
public:
    // some stuff

private:
    char *suit[ 4 ];
};

Where I can initialize this array in such a way? char开发者_Python百科 *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" } I guess it can be done using constructor, but I don't know how exactly to do it.


You could create it as a static variable in the class, like this:

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;
}


Try this:

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

If that doesn't work, then your compiler doesn't support that feature of C++ yet. So you'll need to do it the old fashion way:

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

If you're going to use char pointers like that though, you should make them const, i.e.:

const char *suit[ 4 ];

Reason being, you can't modify the strings anyway, string literals reside in read-only memory. By declaring it const, at least the compiler will tell you your problem if you try to modify it. Better to avoid all that and just use std::string.

0

精彩评论

暂无评论...
验证码 换一张
取 消