如何初始化作为类成员的数组? [英] How to initialize an array that is a member of a class?
本文介绍了如何初始化作为类成员的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如我有一个类叫DeckOfCards和数组char * suit [4]。
For example I have a class called DeckOfCards and array char *suit[ 4 ].
class DeckOfCards
{
public:
// some stuff
private:
char *suit[ 4 ];
};
我可以用这种方式初始化这个数组? char * suit [4] = {Hearts,Diamonds,Clubs,Spades}
我想可以使用构造函数,
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.
推荐答案
您可以在类中创建一个静态变量,如下所示:
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;
}
这篇关于如何初始化作为类成员的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文