我有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',您拒绝让我们看到了它的'析构函数。我建议使用调试器,逐步执行代码,并确定它来自哪里。 –