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

时间:2010-08-01 18:43:30

标签: c++ arrays constructor initialization

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

在构造函数中的这两行: 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];

    }

4 个答案:

答案 0 :(得分:5)

根据您发布的代码,我认为明文suitsdenominations应该是静态数据成员,即每个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

您必须手动复制数组(或使用vectorboost::array之类的容器。

答案 2 :(得分:4)

如果您收到ICE(内部编译器错误),那么您真的应该将代码报告给编写编译器的人。编译器应该打印出警告和错误,但不打印分段错误。

答案 3 :(得分:3)

使用std::vectorboost::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;
}