C++保存对象的问题?
怪我咯
怪我咯 2017-04-17 13:16:00
0
4
485
//这是测试用的类
class A {
public:
    int _i;
    string _str;
    vector<int> _vec;
    A(const int i = 0, const string str = "hi", vector<int> vec = { 0 }) 
    :_a(i), _b(str), _vec(vec) {}
};

//这是第一次测试,输出是正确的
int main()
{
    A a(1, "hello", { 1,2,3 });
    ofstream out("test.txt", ios::binary);
    out.write((char*)&a, sizeof(a));
    out.close();

    A b;
    ifstream in("test.txt", ios::binary);
    in.read((char*)&b, sizeof(b));
    in.close();
    cout << b._i << b._str << *b._vec.begin();
    getchar();
}

//然后我把写入文件的部分注释掉了,程序就不能用了
int main()
{
    /*A a(1, "hello", { 1,2,3 });
    ofstream out("test.txt", ios::binary);
    out.write((char*)&a, sizeof(a));
    out.close();*/
    
    A b;
    ifstream in("test.txt", ios::binary);
    in.read((char*)&b, sizeof(b));
    in.close();
    cout << b._i << b._str << *b._vec.begin();
    getchar();
}
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(4)
刘奇

Only POD without pointers can write the entire struct directly into the file. This is like being fooled by junk textbooks. The same goes for our textbooks back then.

PHPzhong

Because string and vector contain pointers to the heap area.

Every time the program runs, it is not necessarily allocated to one place. What you read next time is junk data.

You should find a way to save its actual data, find a json library or something.

伊谢尔伦

What you save is a reference to the object. The data on the stack is stored, but the data on the heap is not.
Different string implementations may result in inconsistent sizes of class objects

A b;
ifstream in("test.txt", ios::binary);
in.read((char*)&b, sizeof(b));

It may sound confusing

洪涛

There is no problem in saving basic data types, but string and vector cannot. Otherwise, you can implement one yourself, like c

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template