gpt4 book ai didi

C++ 构造函数错误。无法初始化字符串数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:08:55 25 4
gpt4 key购买 nike

为什么不能在我的构造函数中初始化我的字符串数组?我收到以下错误:内部编译器错误:段错误|

构造函数中的这两行:花色 = {“梅花”、“方 block ”、“红心”、“黑桃”};面额 = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen""国王"};

class Card
{
public:
Card(int n);
Card(string d, string s);
int getNumber();
string getDenomination();
string getSuit();
void setNumber(int n);
void setDenomination(string d);
void setSuit(string s);
void printMe();
void compareMe(Card c);

private:
int number;
string denomiation;
string suit;
string suits [4];
string denominations [13];
};


Card::Card(int n)
{
suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
denominations = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};

int denIndex, suitIndex;

denIndex = 51 % 13;
suitIndex = 51 / 13;

number = n;
denomiation = denominations[denIndex];
suit = suits[suitIndex];

}

最佳答案

根据您发布的代码,我猜这些人 suitsdenominations应该是静态数据成员,也就是说它们对于每个 Card 总是有相同的数据实例。

所以我建议您将它们设为静态并在您的 cpp 文件中的文件范围内初始化它们(在您的类声明之外):

声明:

class Card
{
public:
Card(int n);
Card(string d, string s);
int getNumber();
string getDenomination();
string getSuit();
void setNumber(int n);
void setDenomination(string d);
void setSuit(string s);
void printMe();
void compareMe(Card c);

private:
int number;
string denomiation;
string suit;
static const string suits [4]; // static const
static const string denominations [13]; // static const
};

定义:

const string Card::suits[4] = {"Clubs", "Diamonds", "Hearts", "Spades"};
const string Card::denominations[13] = {"Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"};

编辑:正如罗伯特·巴恩斯所说,让他们成为static const甚至更好。

希望对您有所帮助。

关于C++ 构造函数错误。无法初始化字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3383255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com