我正在尝试将复杂对象保存到文件,像这样在复杂对象中重载<>运算符

class Data {
public:
    string name;
    double rating;

friend std::ostream& operator<<(std::ostream& o, const Data& p)
{
    o << p.name << "\n";
    o << p.rating << "\n";
    return o;
}

friend std::istream& operator>>(std::istream& o, Data& p)
{
    o >> p.name >> p.rating;
    return o;
}
}


然后,我正在使用运算符尝试将对象数组保存到文件中。
这是包含所有文件相关方法的类:

class FileSave
{
public:
FileSave()
{
    openFile();
    load();
}

~FileSave()
{
    if(editm)
        outfile.close();
    else
        infile.close();
}

void openFile()
{
    if(editm)
        outfile.open("flatsave.elo", ios::out | ios::binary);
    else
        infile.open("flatsave.elo", ios::in | ios::binary);
}

void closeFile()
{
    if(editm)
        outfile.close();
    else
        infile.close();
}

void save()
{
    changemode(true);
    outfile << people << endl;
}

void load()
{
    changemode(false);
    for(int i=0; i < 10; i++)
    {
        infile >> people[i];
    }
}

void changemode(bool editmode)
{
    if(editm != editmode)
    {
        closeFile();
        editm = editmode;
        openFile();
    }
}
private:
ofstream outfile;
ifstream infile;
bool editm = false;
};


人员是数据对象的数组。

我尝试注释掉各种位,但是错误仍然发生,其他线程说我的重载的标题是错误的,但是我只是一个字母一个字母地复制,因此对此感到有些困惑。

提前致谢。

最佳答案

您对流的使用无效。使用流作为成员时,需要确保封装对象不可复制。

如果添加FileSave(const FileSave&) = delete;(或将其声明为私有且未实现-如果您在c ++ 11之前工作),则(我认为)会将编译错误更改为与FileSave有关的错误(如代码所示)正在某处复制FileSave,但由于无法复制流而无法实现)。

不要将流对象保留在类范围内,而应考虑在函数中对流对象进行作用域定义:

void demo_function()
{
    using namespace std;

    // "Where people is the array of the Data object"
    vector<Data> people;

    // load:
    ifstream in{ "flatsave.elo" };
    copy( istream_iterator<Data>{ in }, istream_iterator<Data>{},
        back_inserter(people) );

    // save:
    ofstream out{ "flatsave.elo" }; // will be flushed and saved
                                    // at end of scope
    copy( begin(people), end(people),
        ostream_iterator<Data>{ out, "\n" };

} // will flush out and save it and close both streams

09-10 01:32