【发布时间】:2025-12-22 14:25:20
【问题描述】:
我正在尝试从一个文件中读取两个值并将它们存储在我的名为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;
}
例如,如果我阅读宙斯,希腊语,那么我将如何访问它们?
我收到的错误是:
错误:
cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'|
【问题讨论】:
-
您可以创建一个
std::map<string, God>,这样您就可以按名称访问对象。 -
你需要定义获取成员函数来访问你的成员
-
您遇到了什么问题?您的标题表明您想知道如何在容器中存储值。
-
与你的问题无关,但你不应该做
while (!inFile.eof()),这是因为eofbit标志直到之后你试图阅读超出结尾文件。这会导致循环重复一次到多次。相反,例如while (inFile >> ...). -
我知道如何将值存储到像
list<double>这样的容器中,但现在我想知道如何将上帝存储在容器中,然后分别访问名称和神话。感谢@Joachim Pileborg 的提示
标签: c++ list class containers