了解我的代码中的意外行为

时间:2017-11-19 09:28:58

标签: c++ pointers object persistence

我一直试图通过写入文件并稍后阅读来保持对象,但我无法使其工作。有人帮我理解我的错误?

**

while (c < m_size) {
        // Either tmp or *tmp gives null, but has valid value in debugger, don't know what I am doing wrong here :(
        std::cout << c << " byte = " << *tmp << std::endl;
        tmp++; c++;
    }
    // File is empty either if use tmp or (char*) this
    out.write(tmp, m_size);

**

这是我的代码基于我在其他地方阅读的一个例子。

#include <iostream>
#include <fstream>

class Persistent
{
public:
    Persistent(int x, int y) : m_size(sizeof(*this)), m_x(x), m_y(y)
    {

    }
    void read(std::ifstream& in);
    void write(std::ofstream& out);
    void print()
    {
        std::cout << "X = " << m_x << " Y = " << m_y << std::endl;
    }

private:
    size_t m_size;
    int m_x, m_y;
};

void Persistent::read(std::ifstream& in)
{
    in.read((char*)this, m_size);
}

void Persistent::write(std::ofstream& out)
{
    char *tmp = (char*)this;
    int c = 0;
    while (c < m_size) {
        // Either tmp or *tmp gives null, but has valid value in debugger, don't know what I am doing wrong here :(
        std::cout << c << " byte = " << *tmp << std::endl;
        tmp++; c++;
    }
    // File is empty either if use tmp or (char*) this
    out.write(tmp, m_size);
}

int main()
{
    Persistent p1(5, 8);

    // Write object to File
    std::ofstream out("MyObject.dat");
    p1.write(out);

    Persistent p2(0,0);

    // Read object from filee
    std::ifstream in("MyObject.dat");
    p2.read(in);
    p2.print();

    return 0;
}

由于

编辑:自己排序。只需要在写入之后刷新流以使其工作(因为它没有写入),并且还必须将字节转换为int以查看它们之前被解释为ASCII的值。

0 个答案:

没有答案