【发布时间】:2015-08-18 15:34:03
【问题描述】:
我在Flashcard.h 和Flashcard.cpp 中声明了Flashcard 类。我想创建一个CardList 类,它应该存储std::vector<Flashcard> 以及其他一些信息,并提供一些操作方法。
CardList.h
#include <vector>
#ifndef LC_FLASHCARD
#include "Flashcard.h"
#endif
class CardList
{
public:
/* Constructor */
CardList (int number_of_cards = 1);
/* Returns the j'th card. */
Flashcard getCard ( int j );
/* Replaces the j'th card with new_card. */
void setCard ( int j, Flashcard new_card );
/* ... */
private:
std::vector<Flashcard> card_list;
/* ... */
};
CardList.cpp
#include "CardList.h"
CardList::CardList ( int number_of_cards ) {
std::vector<Flashcard> card_list(number_of_cards);
}
CardList::~CardList ( void ) { }
Flashcard CardList::getCard ( int j ) {
return this->card_list[j];
}
void CardList::setCard ( int j, Flashcard new_card ) {
this->card_list[j] = new_card;
}
Flashcard CardList::drawCard ( void ) {
return this->getCard(0);
}
问题
每当我调用CardList::getCard 或CardList::setCard 时,我都会遇到段错误。例如:
#include "Flashcard.h"
#include "CardList.h"
/* ... */
int main( int argc, char** argv ) {
/* Creates flashcard card */
Flashcard card;
/* (do things to card) */
CardList card_list(7);
std::cout << "Declaration and initialisation of card_list successful" << std::endl;
card_list.setCard(0, card); // *** SEGFAULT ***
std::cout << "Assignment successful" << std::endl;
/* ... */
return 0;
}
我认为问题在于我的构造函数CardList::CardList,但我该如何解决呢?
【问题讨论】:
-
我怀疑您的错误出现在
Flashcard的复制构造函数或析构函数中,您拒绝让我们看到它。我建议使用调试器,单步调试您的代码,并确定它的来源。