问题
I'm trying to print every element inside a vector like this:
vector<users>::iterator i;
for(i = userlist.begin(); i<userlist.end(); i++)
{
cout << *i << "\n";
}
Then I'm getting an error like this:
no match for 'operator<<' in 'std::cout << (&i)->__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = users*, _Container = std::vector<users, std::allocator<users> >]()'
Is it anything obvious I've missed?
回答1:
Have you defined a function with this signature?:
std::ostream & operator<<(std::ostream &, const users &);
It should not be a member function of users, although it may or may not be a friend, up to you. The prototype should go in the header file of class users, and the body should go in the source(.cpp) file. I have no idea how your users class is defined, or how you would want to format the output, but the function definition should look something like this:
std::ostream & operator<<(std::ostream & os, const users & U)
{
os << U.some_data_members;
os << U.and_or_some_member_functions();
os << whatever;
return os;
}
回答2:
Once you've defined std::ostream &operator<<(std::ostream &, user&);
, consider changing your code to use std::copy
instead of a for
loop:
// leaving off the `std::`, you're not using it for `cout`.
//
copy(userlist.begin(), userlist.end(), ostream_iterator<user>(cout, "\n"));
回答3:
Have you defined stream operator for the users class? If not, do so.
回答4:
You need to write an overload of ostream::operator<<()
that takes a an instance of users
, or write some conversion operator that will provide an auto-conversion from user
to some type that one of the operator<<()
versions knows about.
回答5:
You need to define your own public function operator<< taking parameters of an ostream and a users:
std::ostream& operator<<(std::ostream&, users&);
Sorry, is it users
or user
?
来源:https://stackoverflow.com/questions/5707827/no-match-for-operator-in-stdcout