2015-08-18 33 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); 
} 
相关问题