#include <iostream>
#include <vector>
using namespace std;
class Book
{
int isbn;
string price;
public:
void setDetails()
{
cout << "ISBN ?" ;
cin >> isbn;
cout << "Price ?";
cin >> price;
}
void getDetails()
{
cout << "ISBN: " << isbn;
cout << "Price: " << price;
}
};
int main()
{
int a;
vector<Book> books;
cout << "How many books to insert ?";
cin >> a;
for(int i = 0; i < a; i++)
{
books[i].setDetails();
}
for(int j = 0; j < a; j++)
{
books[j].getDetails();
}
}
当我运行程序时,在我输入isbn值后的那一刻,程序崩溃了。我找不到出了什么问题。 我的主要功能有问题吗?
答案 0 :(得分:3)
你没有在向量中推送任何元素。您需要使用push_back
或resize
int a;
vector<Book> books;
cout << "How many books to insert ?";
cin >> a;
books.resize( a ); // added by jpo38
for(int i = 0; i < a; i++)
{
books[i].setDetails();
}
for(int j = 0; j < a; j++)
{
books[j].getDetails();
}
答案 1 :(得分:2)
你的矢量是空的。尝试添加以下行:
vector<Book> books;
cout << "How many books to insert ?";
cin >> a;
// Add this line:
books.resize(a);
答案 2 :(得分:1)
尝试像这样更改它,我尝试了它,
int a;
cout << "How many books to insert ?";
cin >> a;
vector<Book> books(a);
即先获取大小并构造具有该大小的向量,这样就不会遇到分段错误