如何用对象向量重载 cin(>>)

How can i overload cin(>>) with vector of object

本文关键字:gt cin 何用 对象 向量 重载      更新时间:2023-10-16

若标题不能让你们理解这个问题。下面是我试图用代码做的代码片段。我有类Book对象的向量,我想一次为Book对象输入,所以我想重载它。在推回操作中,它要求类的>>版本。所以我做了这个,但仍然无法接受输入

class Book{
friend istream &operator>>(istream &in,Book &b);
string name;
unsigned int id;
unsigned int no;
};
class Booklist{
vector<Book>b;
void addBook();
};
istream &operator>>(istream &in,Book &b)
{
// cout<<"Enter book id , no and name :"<<endl; as suggested lets discard it but still its error prone
cin>>b.id>>b.no>>b.name;
return in;
}
void Booklist::addBook()
{
int check;
while(cin>>check){
try{
cout<<"Enter book serial number - "<<endl;
cin>>b.push_back(); // Here is the error part
if(cin){
throw runtime_error("Input failed.n");}
}
catch(runtime_error error){
cout<<error.what()
<<"Try again? Enter y or n.n";
char c;
cin>>c;
if(!cin || c=='n'){
break;
}
}
}
}


***ERRORS IN COMPILER***
In member function 'void Booklist::addBook()':|
no matching function for call to 'std::vector<Book>::push_back()'|
note: candidate: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = Book; _Alloc = std::allocator<Book>; std::vector<_Tp, _Alloc>::value_type = Book]|
candidate expects 1 argument, 0 provided|
candidate: void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = Book; _Alloc = std::allocator<Book>; std::vector<_Tp, _Alloc>::value_type = Book]|
note:   candidate expects 1 argument, 0 provided|

您在这里的基本误解是函数push_back()(注意空括号(不存在,编译器不知道如何将其与cin >>结合使用。

push_back(Book b)确实存在,但您必须提供一个临时Book对象,例如:

Book book;
cin >> book; // no more error
b.push_back(book);