search

Home  >  Q&A  >  body text

C++保存对象的问题?

//这是测试用的类
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();
}
怪我咯怪我咯2803 days ago478

reply all(4)I'll reply

  • 怪我咯

    怪我咯2017-04-17 13:18:00

    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.

    reply
    0
  • PHPz

    PHPz2017-04-17 13:18:00

    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.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:18:00

    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

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:18:00

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

    reply
    0
  • Cancelreply