在std :: cout中与'operator <<'不匹配

Kah*_*ahn 2 c++ cout

我正在开发gsoap web服务,我正在检索对象的向量以回复查询.我有两种方法可以做到:首先是简单循环和迭代器.他们都没有工作.

错误是:

错误:不匹配'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);

}
Run Code Online (Sandbox Code Playgroud)

很明显,操作符重载operator<<cout的问题.我看过几个与此相关的问题,但没有人帮助过我.如果有人可以提供一个如何解决它的具体例子,我将非常感激.(请不要一般性地谈论它,我是C++的新手,我花了三天时间来寻找解决方案.)

jua*_*nza 6

您需要提供输出流运算符PersonInfo.像这样的东西:

struct PersonInfo
{
  int age;
  std::string name;
};

#include <iostream>
std::ostream& operator<<(std::ostream& o, const PersonInfo& p)
{
  return o << p.name << " " << p.age;
}
Run Code Online (Sandbox Code Playgroud)

此运算符允许类型的表达式A << B,其中A是一个std::ostream实例(其中std::cout一个BPersonInfo实例)并且是一个实例.

这允许你做这样的事情:

#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;
}
Run Code Online (Sandbox Code Playgroud)

这反过来允许您打印取消引用的迭代器.