2016-04-25 68 views
0

我有一個名爲book的類,它包含書籍。std :: push_back期間的向量分段錯誤

#ifndef BOOK_H 
#include<string> 
#include<vector> 
#include<iostream> 
#define BOOK_H 
class book 
{ 
public: 
    std::string Author, Title; 
    int Year; 
    book(){} 
    book(std::string author, std::string title, int year); 
    ~book(){} 
    void add_book(); 
    std::vector<book*>library; 
}; 
#endif 

book.cpp文件

#include "book.h" 

book::book(std::string author, std::string title, int year) 
:Author(author), Title(title), Year(year){} 

void book::add_book() 
{ 
    int y; 
    std::string a, t; 
    std::cin>>a; 
    std::cin>>t; 
    std::cin>>y; 
    library.push_back(new book(a, t, y)); 
} 

但是,當我想一個新的book添加到庫中,我得到在main.cpp中文件中的新對象的push_back期間分割故障

#include "book.h" 

int main() 
{ 
    book* ptr; 
    ptr->add_book(); 
    return 0; 
} 

有人可以向我解釋是什麼問題?

我是OOP的新手,儘管我在這裏看過很多帖子,但我仍然無法找到解決方案。

+1

對於每本書都有單獨的庫的想法對我來說看起來有點不妥。你也聲明'book *',但是不要初始化它,然後調用它的一個方法。 – apokryfos

+0

你曾經去過圖書館或看書嗎? – molbdnilo

+0

我知道它看起來如此,但這只是爲了練習。 是的,我有 –

回答

2

您並未初始化main中的ptr;

int main() 
{ 
    book* ptr = new book(); // initialize it here 
    ptr->add_book(); 
    return 0; 
} 

這將修復段錯誤,但是,我不確定與示例代碼相關的邏輯以及可能的內存泄漏。


我會看到librarybook型分離爲更好的構圖,並避免堆分配;

#include<string> 
#include<vector> 
#include<iostream> 

class book 
{ 
public: 
    std::string Author, Title; 
    int Year; 
    book(){} 
    book(std::string author, std::string title, int year) : Author(author), Title(title), Year(year) {} 
    ~book(){} 
}; 

struct library { 
    std::vector<book> books_; 
    void add_book(const book& value) { books_.push_back(value); } 
}; 

int main() 
{ 
    library lib; 
    int y; 
    std::string a, t; 
    std::cin>>a; 
    std::cin>>t; 
    std::cin>>y; 
    lib.add_book(book(a, t, y)); 
    return 0; 
} 
1

那麼,在這裏:

book* ptr; 
ptr->add_book(); 

ptr是未分配的,所以它的使用使賽格故障。您應該在使用前指定它:

ptr = new book();

這將導致內存泄漏所以我建議(如果你喜歡動態分配):

auto ptr = std::make_unique<book>(); 
ptr->add_book(); 

但是,爲什麼你需要有一個指針,無論如何,這樣的:

book bk; 
bk.add_book(); 

將同樣的方式工作。


在另一方面,爲什麼你book類保持book實例的載體?你需要一個library類,它將保持書的向量。

+0

感謝您的解釋。我會記住這一點,不幸的是我現在正在使用C++ 11編譯器。 現在不能回答這個問題。我必須練習更多:)但是再次感謝創造第二課的想法。 –

1

在使用它的方法之前,您必須創建一個Book類的對象。

Book *ptr = new Book();