【问题标题】:Using this pointer to write object to binary file in c++在 C++ 中使用此指针将对象写入二进制文件
【发布时间】:2020-05-26 04:46:07
【问题描述】:
void Employee::store_data(string filename) {
    fstream file;
    file.open(filename,ios::app | ios::binary);
    if (file) {
        file.write((char*)&this,sizeof(this));
        file.close();
    }
    else cout<<"\n Error in Opening the file!";

}

这是我尝试过的。 我想将员工类的当前对象以二进制模式存储到文件中。 但我明白了这个

error: lvalue required as unary '&' operand
     file.write((char*)&this,sizeof(this));

【问题讨论】:

    标签: c++ object file-handling ostream this-pointer


    【解决方案1】:

    this 不是实际变量,因此您无法获取其地址。但它已经一个指针,所以你不需要。它也有一个指针的大小,所以你的sizeof 是错误的。然后在 C++ 中,你不应该使用 C 风格的强制转换。所以修复这三件事,你的线路就变成了

    file.write(reinterpret_cast<char*>(this), sizeof(*this));
    

    应该可以编译。

    但是,请注意,如果 Employee 包含任何复杂的内容,例如std::string 成员变量、指针成员变量、虚方法、构造函数/析构函数等,则无法读取回数据。在这种情况下,该写入不会写入所有内容,或者写入错误的运行时值,并且您会返回垃圾。你进入了可怕的未定义行为领域,任何事情都可能发生(包括在你测试它时显然有效的事情)。

    【讨论】:

    • 那么我应该怎么做才能避免垃圾值?
    【解决方案2】:

    该语言不允许使用 &amp;this 作为表达式,因为 (https://timsong-cpp.github.io/cppwp/n3337/class.this#1)

    关键字this是prvalue表达式

    您只能在左值表达式上使用addressof (&amp;) 运算符。

    更重要的是,你需要使用

    file.write(reinterpret_cast<char const*>(this), sizeof(*this));
    

    保存对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 2015-07-03
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      相关资源
      最近更新 更多