将值存储在容器中

时间:2014-09-14 20:06:02

标签: c++ list class containers

我正在尝试从文件中读取两个值,并将它们存储在名为God的类中。 God有两个数据成员namemythology。我希望将值存储在list<God>(上帝及其各自的神话)中,然后打印出来。到目前为止,这是我的代码:

#include <iostream>
#include <fstream>
#include <list>
#include <string>

using namespace std;

class God {
    string name;
    string mythology;
public:
    God(string& a, string& b) {
        name=a;
        mythology =b;
    }
    friend ostream&  operator<<( ostream& os,const God&);
};

void read_gods(list<God>& s) {
    string gname, gmyth;

    //reading values from file
    ifstream inFile;
    inFile.open("gods.txt");

    while(!inFile.eof()) {
        inFile >> gname >> gmyth ;
        s.push_back(God(gname, gmyth));
    }
}

ostream& operator<<( ostream& os,const God& god) {
    return  os << god.name << god.mythology;
}

int main() {
    //container:
    list<God> Godmyth;
    read_gods(Godmyth);

    cout << Godmyth;

    return 0;
}

例如,如果我在Zeus中读到希腊语,那么我将如何访问它们?

我收到的错误是:

  

错误:cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'|

2 个答案:

答案 0 :(得分:1)

您应该为上帝输出operator <<或某个成员函数,以输出其数据成员。

例如

class God
{
public:
   std::ostream & out( std::ostream &os ) const
   {
      return os << name << ": " << mythology;
   }

   //...
};

或者

class God
{
public:
   friend std::ostream & operator <<( std::ostream &, const God & ); 

   //...
};


std::ostream & operator <<( std::ostream &os, const God &god )
{
    return os << god.name << ": " << god.mythology;
}     

在这种情况下,而不是无效的陈述

cout << Godmyth << endl;
你可以写

for ( const God &god : Godmyth ) std::cout << god << std::endl;

或者,如果您只是想访问数据成员,那么您应该编写getter。

例如

class God
{
public:
    std::string GetName() const { return name; }
    std::string GetMythology() const { return mythology; }
    //...

答案 1 :(得分:0)

没有超载operator<<允许使用std::cout打印std::list的内容。

你可以做什么?

  1. 正如@Vlad所说,你可以写

    for ( const God &god : Godmyth )
        std::cout << god << '\n';
    
  2. 或者,您可以编写自己的operator<<

    template<typename T>
    std::ostream& operator<< (std::ostream &os, const std::list<T> &_list){
        os << "[\n";
        for ( const auto &item : _list )
            os << item << ";\n";
        return os << ']';
    }
    
相关问题