std::ios_base::ios_base(const std::ios_base&) 是私有的

std::ios_base::ios_base(const std::ios_base&) is private

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

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;
}
}

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

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;
};

其中 people 是数据数组 object。

我已经尝试注释掉各种位,但错误仍然存​​在,其他线程说我的重载 header 是错误的,但我只是一个字母一个字母地复制,所以我有点困惑

提前致谢。

流不是容器;它们是数据流。因此,它们不能被复制,并且在 C++11 之前,强制执行的方式是它们的复制构造函数是 private.

现在,由于您的 class FileSave 包含两个流,这意味着 FileSave 也无法复制! 属性 是可传递的。因此,您必须确保您不会尝试这样做,在这些成员周围引入一些间接的方法。

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

如果您添加 FileSave(const FileSave&) = delete;(或将其声明为私有但不实现它 - 如果您使用的是 c++11 之前的版本),您将(我认为)将编译错误更改为关于 FileSave 的一个(因为代码可能正在某处制作 FileSave 的副本并且无法实现,因为无法复制流)。

与其将流对象保留在 class 范围内,不如考虑在函数中限定流对象的范围:

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