没有匹配“ operator<<”的对象在std :: cout中 [英] No match for 'operator<<' in std::cout
问题描述
我正在开发gsoap Web服务,在其中我将检索对象的向量以返回查询。我有两种方法可以做到:首先通过简单循环和迭代器。它们都不起作用。
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.
错误是:
错误:在
'std :: cout
mPer.MultiplePersons :: info.std :: vector<中没有'operator<<'的匹配项; _Tp,_Alloc> :: at< PersonInfo,std :: allocator< PersonInfo> >((((std :: vector< PersonInfo> :: size_type)i))'
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);
}
很明显,运算符重载 operator< ;
是问题。我研究了与此相关的几个问题,但是没有人帮助我。如果有人可以提供有关如何解决该问题的具体示例,将不胜感激。 (请不要大声谈论它,我是C ++的新手,并且花了三天时间在它上面寻找解决方案。) cout
中的<
It's obvious that operator overloading operator<<
in cout
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.)
推荐答案
您需要为 PersonInfo
提供输出流运算符。像这样:
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;
}
此运算符允许使用 A < < B
,其中 A
是 std :: ostream
实例(其中 std :: cout
是一个),而 B
是 PersonInfo
实例。
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.
这篇关于没有匹配“ operator<<”的对象在std :: cout中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!