【问题标题】:std::ios_base::ios_base(const std::ios_base&) is privatestd::ios_base::ios_base(const std::ios_base&) 是私有的
【发布时间】:2015-02-14 01:04:27
【问题描述】:

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

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

其中 people 是 Data 对象的数组。

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

提前致谢。

【问题讨论】:

  • 给我们完整的错误信息。
  • 您正在尝试在某处复制流(或 FileSave,也许)。
  • 非常模糊的问题。我可以猜出你的问题并告诉你问题是什么,但这不是一个好帖子。

标签: c++ file c++11


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    如果您添加FileSave(const FileSave&amp;) = 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
    

    【讨论】:

    • 嘿,我已经尝试过这种方法,但我在副本中遇到错误,它抱怨 istream_iterator{} 说“在 '{' 标记之前缺少模板参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2015-01-15
    相关资源
    最近更新 更多