如何用对象向量重载 cin(>>)
How can i overload cin(>>) with vector of object
若标题不能让你们理解这个问题。下面是我试图用代码做的代码片段。我有类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);
相关文章:
- C++中的cin.ignore()函数不适用于整个流
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- Problems with std::cin.fail()
- EASTL矢量<向量<int>>连续的
- 由cin中的字符串中未捕获空白引起的分割错误
- 在C++中使用Cin,我如何在1行中输入
- 将 cin 限制为只有一个
- cin >> int 给定一个字符串将 int 赋值为 0
- istream std::cin如何修改自定义istream缓冲区
- C++ 将 CIN 值存储到任何类型的数组中
- 为什么无论你输入什么,这"while(cin.get(str,3))"只运行一次?
- cin 的十进制输入验证?
- Turbo C++ cin() 不能与 gets() 一起使用
- 使用 cin 时接受小数点后的 2 位数字
- 在 std::getline 和 std::cin 期间卡在循环中
- 我无法在Visual Studio代码中使用CIN输入答案,它说输入您的年龄,但它说只读文本编辑器如何解决这个问题?
- 为什么我的两个 cin 语句没有在程序结束时运行?
- C++ cin.ignore() 跳过循环
- CIN是逻辑1还是0?
- 如何运行多行 cin?