为什么无法在构造函数中初始化我的字符串数组?我收到以下错误: 内部编译器错误:分段错误|
在构造函数中的这两行: suit = {“Clubs”,“Diamonds”,“Hearts”,“Spades”}; denominations = {“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];
}
答案 0 :(得分:5)
根据您发布的代码,我认为明文suits
和denominations
应该是静态数据成员,即每个Card
实例的数据总是相同。< / p>
所以我建议你将它们设置为静态并在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"};
修改强>
正如Robert S. Barnes所说,让它们static const
更好。
希望有所帮助。
答案 1 :(得分:4)
您只能在构造时使用文字数组初始化,而不是赋值。
int good[3] = { 1, 2, 3 }; // OK
int bad[3];
bad = { 1, 2, 3 }; // not so good
您必须手动复制数组(或使用vector
或boost::array
之类的容器。
答案 2 :(得分:4)
如果您收到ICE(内部编译器错误),那么您真的应该将代码报告给编写编译器的人。编译器应该打印出警告和错误,但不打印分段错误。
答案 3 :(得分:3)
使用std::vector
或boost::array
,您的代码的简化示例位于
#include <boost/assign/list_of.hpp>
#include <boost/array.hpp>
#include <iostream>
#include <string>
class Card
{
public:
explicit Card( unsigned n ) :
_number( n ),
_suits( boost::assign::list_of( "Clubs" )( "Diamonds" )( "Hearts" )( "Spades" ) ),
_denominations( boost::assign::list_of( "Ace" )( "2" )( "3" )( "4" )( "5" )( "6" )( "7" )( "8" )( "9" )( "10" )( "Jack" )( "Queen" )( "King" ) )
{
}
private:
unsigned _number;
boost::array<std::string, 4> _suits;
boost::array<std::string, 13> _denominations;
};
int
main()
{
Card foo( 5 );
return 0;
}