将对象写入c++; 当我在C++中把一个对象写到二进制文件时,我感到困惑。当我将字符串写入文件时,如下所示: //write a string to a binary file ofstream ofs("Test.txt", ofstream::binary | ofstream::app); string foo = "This is a long .... string." ofs.write((char*)&foo, sizeof(foo)); ofs.close();
但是它写了其他东西(可能是指针)指向文件,而不是字符串本身 当我编写一个类的对象(它有一个字符串成员)时,它工作了将对象写入c++; 当我在C++中把一个对象写到二进制文件时,我感到困惑。当我将字符串写入文件时,如下所示: //write a string to a binary file ofstream ofs("Test.txt", ofstream::binary | ofstream::app); string foo = "This is a long .... string." ofs.write((char*)&foo, sizeof(foo)); ofs.close();,c++,C++,但是它写了其他东西(可能是指针)指向文件,而不是字符串本身 当我编写一个类的对象(它有一个字符串成员)时,它工作了 // a simple class class Person { public: Person() = default; Person(std::string name, int old) : fullName(name), age(old) {} std::string getName() const { return this->fullName;
// a simple class
class Person {
public:
Person() = default;
Person(std::string name, int old) : fullName(name), age(old) {}
std::string getName() const { return this->fullName; }
int getAge() const { return this->ID; }
private:
string fullName;
int age;
};
int main()
{
std::ofstream ofs("Test.txt", std::ofstream::binary | std::ofstream::app);
Person p1("lifeisamoive", 1234);
ofs.write((char*)&p1, sizeof(Person));
ofs.close();
Person *p2 = new Person();
std::ifstream ifs("Test.txt", std::ifstream::binary);
//output the right information
while(ifs.read((char*)p2, sizeof(Person)))
std::cout << p2->getName() << " " << p2->getAge() << std::endl;
else
std::cout << "Fail" << std::endl;
ifs.close();
return 0;
}
//一个简单的类
班主任{
公众:
Person()=默认值;
Person(std::string name,int-old):全名(name),年龄(old){}
std::string getName()常量{返回此->全名;}
int getAge()常量{返回此->ID;}
私人:
字符串全名;
智力年龄;
};
int main()
{
std::ofstreamofs(“Test.txt”,std::ofstream::binary | std::ofstream::app);
第p1人(“lifeisamoive”,1234);
ofs.write((字符*)和p1,sizeof(个人));
ofs.close();
Person*p2=新的Person();
std::ifstream-ifs(“Test.txt”,std::ifstream::binary);
//输出正确的信息
而(如果读取((char*)p2,sizeof(Person)))
std::cout getName()您正在读取person对象的内存地址。person对象由一个string对象和一个int对象组成。当程序仍在运行时,从内存中读取这些值意味着与通过=运算符复制对象相同。string对象包含指向堆的指针,实际文本保留在堆中。存储对象时对于文件,您存储指针,但不存储指针指向的内容
在第二个示例中,您读取了p1到p2中实际字符数组的指针,由于p1仍然存在,您可以看到相同的名称。但是,您仍然存在相同的问题,您实际上没有将实际可读字符串存储到文件中
您不应该存储带有指向堆到文件的指针的对象。您不能仅通过强制转换将字符串转换为字符指针。您应该改用c_str()。请尝试以下操作:
ofstream ofs("Test.txt", ofstream::binary | ofstream::app);
string foo = "This is a long .... string."
ofs.write(foo.c_str(), foo.size());
ofs.close();
是的,我知道了。我理解为什么不建议直接将对象写入文件,特别是当您不确定该类是否为POD类型时。谢谢。