视觉C++ 尝试重载 ifstream 以将文件读入类的数组

visual C++ Trying to Overload ifstream to read file into a Class's array

本文关键字:文件 数组 C++ 重载 ifstream 视觉      更新时间:2023-10-16

我试图重载ifstream操作符>>,以便从文本文件中读取数据,并将数据放在属于State的类中。

我正在读取的文件格式是州名>州首府>人口。我只是想把状态名读入数组。

我一直遇到操作符重载的问题。我有点理解它,并能够使ostream工作,但阅读已被证明是更困难的。

不确定这是否有影响,但这是学校的作业,我还在做。只是不知道该往哪里走。

main.cpp

这是我的主CPP文件。

#include <iostream>
#include <string>
#include <fstream>
#include "State.h"
using namespace std;
int main(){
    State s, h;
    string null;
    ifstream fin("states.txt");
    while(fin.good())
    {   
        fin >> h;       //This doesn't read anything in. 
        fin >> null;    //Dumping the Capital City to a null string
        fin >> null;    //Dumping the Population to a null string   
    }
    cout << s;          //Testing my overloaded << operator
    system("pause");
    return 0;
}

State.cpp

这是一个次要CPP文件。

#include "State.h"
#include <fstream>
#include <string>
#include <iostream>
    using namespace std;
int i = 0;
string name, x, y;
State::State()
{
    arrayStates[50];
}
//Trying to overload the input from fstream
ifstream& operator >> (ifstream& in, State h)
{
    for(i = 0; i < 21; i++)
    {
        in >> h.arrayStates[i];
    }
    return in;
}
ostream& operator << (ostream& out, State s)
{
    for(int i = 0; i < 21; i++)
    {
        out << s.arrayStates[i] << endl;
    }
    return out;
}

State.h

这是包含类的头文件。

#include <iostream>
#include <string>
using namespace std;
class State{
private:
    string arrayStates[50];
public:
    State();
    friend ostream& operator << (ostream& out, State s);
    friend ifstream& operator >> (ifstream& in, State h);
};

错误在此函数中,如您所建议的。

ifstream& operator >> (ifstream& in, State h)
{
    for(i = 0; i < 21; i++)
    {
        in >> h.arrayStates[i];
    }
    return in;
}

该函数生成State临时副本,调用该副本h,并初始化该副本。

通过引用传递原State。所以它指的是指向同一个对象。

ifstream& operator >> (ifstream& in, const State &h)