No match for 'operator<<' in std::cout
Solution 1
You need to provide an output stream operator for PersonInfo
. Something like this:
struct PersonInfo
{
int age;
std::string name;
};
#include <iostream>
std::ostream& operator<<(std::ostream& o, const PersonInfo& p)
{
return o << p.name << " " << p.age;
}
This operator allows expressions of the type A << B
, where A
is an std::ostream
instance (of which std::cout
is one) and B
is a PersonInfo
instance.
This allows you do do something like this:
#include <iostream>
#include <fstream>
int main()
{
PersonInfo p = ....;
std::cout << p << std::endl; // prints name and age to stdout
// std::ofstream is also an std::ostream,
// so we can write PersonInfos to a file
std::ofstream person_file("persons.txt");
person_file << p << std::endl;
}
which in turn allows you to print the de-referenced iterator.
Solution 2
The result of *it
is an L-value of type PersonInfo
. The compiler is complaining that there is no operator<<
which takes a right-hand side argument of type PersonInfo
.
For the code to work, you need to provide such an operator, for example like this:
std::ostream& operator<< (std::ostream &str, const PersonInfo &p)
{
str << "Name: " << p.name << "\nAge: " << p.age << '\n';
return str;
}
The exact implementation of the operator depends on your needs for representing the class in output, of course.
Kahn
Updated on March 17, 2020Comments
-
Kahn about 4 years
I am developing gsoap web service where I am retrieving vectors of objects in return of a query. I have two ways to do it: first by simple loop and by iterator. None of them working.
The error is:
error: no match for
'operator<<'
in'std::cout mPer.MultiplePersons::info.std::vector<_Tp, _Alloc>::at<PersonInfo, std::allocator<PersonInfo> >(((std::vector<PersonInfo>::size_type)i))'
MultiplePersons mPer; // Multiple Person is a class, containing vector<PersonInfo> info std::vector<PersonInfo>info; // PersonInfo is class having attributes Name, sex, etc. std::vector<PersonInfo>::iterator it; cout << "First Name: \t"; cin >> firstname; if (p.idenGetFirstName(firstname, &mPer) == SOAP_OK) { // for (int i = 0; i < mPer.info.size(); i++) { // cout << mPer.info.at(i); //Error //} for (it = info.begin(); it != info.end(); ++it) { cout << *it; // Error } } else p.soap_stream_fault(std::cerr); }
It's obvious that operator overloading
operator<<
incout
is the problem. I have looked at several problems related to this, but no one helped me out. If someone can provide a concrete example on how to solve it, it would be very appreciated. (Please do not talk in general about it, I am new to C++ and I have spent three days on it searching for solution.)