2016-04-25 67 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();