Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在c++;_C++_Oop_Object_Fstream_Ofstream - Fatal编程技术网

C++ 在c++;

C++ 在c++;,c++,oop,object,fstream,ofstream,C++,Oop,Object,Fstream,Ofstream,我有一段代码,其中有一类Car,它有一个名为save的成员函数,它使用这个指针将对象保存到一个文件中。我还有一个主要功能,就是我将汽车对象写入另一个文件,但对象保持不变,但是当在记事本中打开两个保存的文件时,它们似乎不同,为什么 #include <iostream> #include <fstream> #include <string> using namespace std; class Car { private: string name;

我有一段代码,其中有一类Car,它有一个名为save的成员函数,它使用这个指针将对象保存到一个文件中。我还有一个主要功能,就是我将汽车对象写入另一个文件,但对象保持不变,但是当在记事本中打开两个保存的文件时,它们似乎不同,为什么

 #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));
}
#包括
#包括
#包括
使用名称空间std;
班车
{
私人:
字符串名;
int模型;
内特纽姆高跟鞋;
公众:
汽车()
{
name=“没有名字”;
模型=0;
numwheels=0;
}
作废保存()
{
流的速度;
open(“filename.txt”,ios::out | ios::app);
写((char*)this,sizeof(this));
}
};
int main()
{
汽车;
//书写对象。。。
car.save();
流的速度;
open(“filename1.txt”,ios::out | ios::app);
ofs.write((char*)和car,sizeof(car));
}
此链接有一个显示结果的图像


sizeof(this)
是指针
Car*
的大小,根据32位或64位平台的不同,其大小为4或8。所以,当您输出对象内存的前4或8个字节时,您可以在图像中看到它。要获得对象大小,您应该使用
sizeof(*this)
sizeof(Car)

实际上我已经解决了这个问题。sizeof(this)语句有一个问题,它返回存储对象的指针的大小,但将其更改为sizeof(Car)将返回对象的大小…”“实际上我已经解决了问题”你呢?更改sizeof的参数不会使两个版本都正确。它将用不同的垃圾数据替换垃圾数据。使用此对象不能使用<代码>写>代码。请在C++中查找序列化。你应该找到足够的资源来学习。