Я пытаюсь прочитать два значения из файла и сохранить их в моем классе под названием " God
. God
есть два члена данных, name
и mythology
. Я хочу сохранить значения в 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;
}
Если, например, я читал в Зевсе, по-гречески, как бы я мог получить к ним доступ?
Ошибка, которую я получаю:
error:
cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'|
Вы должны написать либо operator <<
или некоторую функцию-член для класса God, которая выводит его членов данных.
Например
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;
Или, если вы просто хотите получить доступ к элементам данных, тогда вы должны написать геттеры.
Например
class God
{
public:
std::string GetName() const { return name; }
std::string GetMythology() const { return mythology; }
//...
Нет перегруженного operator<<
разрешить печать std::list
content с помощью std::cout
.
Что ты можешь сделать?
Как сказал @Vlad, вы можете написать
for ( const God &god : Godmyth )
std::cout << god << '\n';
Кроме того, вы можете написать свой собственный 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 << ']';
}
std::map<string, God>
чтобы получить доступ к объектам по имени.