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

问题描述 投票:0回答:1

我一直试图通过写入文件并稍后读取来持久化一个对象,但我无法让它工作。有人帮我理解我的错误吗?

**

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。

c++ pointers object persistence
1个回答
0
投票

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

(这最初是对原始问题的编辑。)

© www.soinside.com 2019 - 2024. All rights reserved.