我有一個名爲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的新手,儘管我在這裏看過很多帖子,但我仍然無法找到解決方案。
對於每本書都有單獨的庫的想法對我來說看起來有點不妥。你也聲明'book *',但是不要初始化它,然後調用它的一個方法。 – apokryfos
你曾經去過圖書館或看書嗎? – molbdnilo
我知道它看起來如此,但這只是爲了練習。 是的,我有 –