我有一个名为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
我知道它看起来如此,但这只是为了练习。 是的,我有 –