简体   繁体   English

如何初始化作为类成员的数组?

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

For example I have a class called DeckOfCards and array char *suit[ 4 ]. 例如,我有一个名为DeckOfCards的类和数组char * suit [4]。

class DeckOfCards
{
public:
    // some stuff

private:
    char *suit[ 4 ];
};

Where I can initialize this array in such a way? 我可以用这种方式初始化这个数组? char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" } I guess it can be done using constructor, but I don't know how exactly to do it. char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" }我想它可以使用构造函数完成,但我不知道究竟是怎么做到的。

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. 如果这不起作用,那么您的编译器还不支持C ++的这个功能。 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, ie: 如果你打算使用这样的char指针,你应该将它们设为const,即:

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. 通过声明const,至少编译器会在您尝试修改它时告诉您问题。 Better to avoid all that and just use std::string . 最好避免所有这些,只使用std::string

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM