2015-08-18 32 views
-5

我有Flashcard.hFlashcard.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::getCardCardList::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,但我怎麼解決?

+1

我懷疑在拷貝構造函數出現在您的錯誤,或Flashcard',您拒絕讓我們看到了它的'析構函數。我建議使用調試器,逐步執行代碼,並確定它來自哪裏。 –

回答

1

此代碼不會做所有你在想什麼:

CardList::CardList (int number_of_cards) { 
    std::vector<Flashcard> card_list(number_of_cards); 
} 

你應該做的是:

CardList::CardList (int number_of_cards) : 
    card_list(number_of_cards) 
{ 
} 

你賽格故障是因爲你從來沒有大小card_list。構造函數版本中的代碼創建了一個不同的臨時card_list,一旦構造函數退出,它就會被銷燬。同時,card_list成員是默認構建的,大小爲零。

+0

謝謝,這是有效的。是':'的例子http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor? –

+0

是的,那個':'和它在構造函數體內通常比賦值好的原因似乎在你連接的這個問題中得到了很好的解釋。 – JSF

0

你的類中有一個名爲card_list的屬性,但是你不需要在你的構造函數中正確地進行初始化。在你的代碼,您有:

CardList::CardList (int number_of_cards) { 
    std::vector<Flashcard> card_list(number_of_cards); 
} 

在這種情況下要初始化local variable命名card_list而不是類的屬性card_list

正確的方法來做到這一點是如下:

CardList::CardList (int number_of_cards) { 
    this->card_list = std::vector<Flashcard>(number_of_cards); 
} 
相關問題