使用c ++中的THIS指针将对象写入文件

时间:2018-04-01 07:04:48

标签: c++ oop object fstream ofstream

所以我有这个代码,其中有一个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));
}

此链接有一个图像,其中显示结果....

https://i.stack.imgur.com/GAyxu.png

1 个答案:

答案 0 :(得分:2)

sizeof(this)是指针Car*的大小,取决于32位或64位平台,为4或8。因此,您输出对象内存的前4或8个字节,您可以在图像中看到它。要获得对象大小,您应该使用sizeof(*this)sizeof(Car)