在C ++中创建对象时出现段错误

时间:2019-03-01 05:59:57

标签: c++

我有以下代码:

Card.h

#include <string>

class Card
{
    public:
        enum suits {Spades, Diamonds, Hearts, Clubs};
        Card(int _suit, int _value);
        std::string SuitToString(int suitidx);
        Card();
        ~Card();
    private:
        int value;
        std::string suit;
};

Card.cpp

#include <string>
#include <vector>
#include "Card.h"

Card::Card() {
}

Card::Card(int _suit, int _value)
{
    this->suit=SuitToString(_suit);
    this->value=_value;
}

Card::~Card()
{
}

std::string Card::SuitToString(int suitidx)
{
    std::vector<std::string> suitStrings = {"Club", "Diamonds", "Hearts", "Spades"};

    return suitStrings[suitidx];
}

Deck.h

#include "Card.h"
#include <vector>

class Deck: public Card {
    public:
        Deck();
        ~Deck();

};

Deck.cpp

#include "Deck.h"
#include <vector>

Deck::Deck()
{
    for (int i=1; i<5; i++) {
        for (int j=1; j<14; j++) {
            Card c(i,j);
            AddCard(c);
        }
    }
}

Deck::~Deck()
{
}

main.cpp

#include "Deck.h"
#include <iostream>

using namespace std;

int main()
{
    Deck d;
    return 0;
}

但是当我运行它时,出现了段错误。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

@tkausl是正确的,您的问题在SuitToString-方法中。您用无效的索引来调用它。