简体   繁体   English

使用该指针将 object 写入 c++ 中的二进制文件

[英]Using this pointer to write object to binary file in c++

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!";

}

this is what i tried.这就是我尝试过的。 I want to store the current object of employee class to a file in binary mode.我想将员工 class 的当前 object 以二进制模式存储到文件中。 but i get this this但我明白了这个

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

this isn't an actual variable, so you can't take its address. this不是一个实际的变量,所以你不能取它的地址。 But it already is a pointer, so you don't need to.但它已经一个指针,所以你不需要。 It also has size of a pointer, so your sizeof is wrong.它也有一个指针的大小,所以你的sizeof是错误的。 And then in C++ you should not use C-style casts.然后在 C++ 中你不应该使用 C 风格的演员表。 So fixing these 3 things, your line becomes所以修复这三件事,你的线路就变成了

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

That should compile.那应该编译。

However , note that if Employee contains anything complex, such as std::string member variables, pointer member variables, virtual methods, constructor / destructor etc, you can't read the data back.但是,请注意,如果 Employee 包含任何复杂的内容,例如std::string成员变量、指针成员变量、虚方法、构造函数/析构函数等,则无法将数据读回。 That write doesn't in that case write everything, or writes wrong runtime values, and you get garbage back.在这种情况下,该写入不会写入所有内容,或者写入错误的运行时值,并且您会返回垃圾。 You enter the dreaded Undefined Behavior territory, anything can happen (including things apparently working when you test it).您进入了可怕的未定义行为领域,任何事情都可能发生(包括在您测试时明显有效的事情)。

The language does not allow use of &this as an expression since ( https://timsong-cpp.github.io/cppwp/n3337/class.this#1 )该语言不允许使用&this作为表达式,因为 ( https://timsong-cpp.github.io/cppwp/n3337/class.this#1 )

the keyword this is a prvalue expression关键字this是纯右值表达式

You can use the addressof ( & ) operator only on lvalue expressions.您只能在左值表达式上使用addressof ( & ) 运算符。

More importantly, you need to use更重要的是,您需要使用

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

to save the object.保存 object。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM