我有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',您拒絕讓我們看到了它的'析構函數。我建議使用調試器,逐步執行代碼,並確定它來自哪裏。 –