【发布时间】:2019-10-23 11:22:12
【问题描述】:
如果标题不会让您理解问题。这是我正在尝试对我的代码执行的代码的 sn-p。 我有类 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|
【问题讨论】:
-
请附上错误信息,它应该对你做错了什么有一些很好的提示
-
您当前的
operator>>函数为Book有两个主要缺陷:首先它不应该打印任何输出,只能读取输入。其次,它应该从作为参数提供的流中读取,而不是从cin中读取(你怎么能从例如文件中读取?)。 -
@foreknownas_463035818 是的,让我们这样做。
-
顺便说一句,使用一致的意图有助于提高可读性
-
而不是为
std::vector<Book>编写operator>>函数,而是使用std::istream_iterator来初始化向量(或任何合适的容器)。您可以为此使用现有的Book流提取运算符。
标签: c++ class vector operator-overloading