[英]Writing an object with a pointer to another object to an ASCII file (C++)
[英]Writing object to a file using THIS pointer in c++
所以我有这段代码,其中有一个Car类,具有一个称为save的成员函数,该函数使用THIS指针将对象保存到文件中。 我也有主要功能,其中我正在将Car对象写入另一个文件,但是对象保持不变,但是当在记事本中打开两个保存的文件时,它们似乎不同吗?
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Car
{
private:
string name;
int model;
int numwheels;
public:
Car()
{
name = "No Name";
model = 0;
numwheels = 0;
}
void save()
{
ofstream ofs;
ofs.open("filename.txt", ios::out | ios::app);
ofs.write((char*)this, sizeof(this));
}
};
int main()
{
Car car;
//writing object...
car.save();
ofstream ofs;
ofs.open("filename1.txt", ios::out | ios::app);
ofs.write((char*)&car, sizeof(car));
}
该链接具有显示结果的图像。
sizeof(this)
是指针Car*
的大小,根据32bit或64bit平台为4或8。 这样,您输出对象存储器的前4或8个字节,就可以在图像中看到它。 要获取对象大小,应使用sizeof(*this)
或sizeof(Car)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.