c++ - 如何重载 std::ofstream::put()?

标签 c++ ofstream

我想将 int16_t 值写入文件。

因此我尝试重载 std::ofstream::put() 方法。

#include <fstream>
#include <cstdint>

class Ofstream : public std::ofstream
{
public:
    Ofstream( const std::string & s) : std::ofstream(s) {}

    // for little-endian machines
    Ofstream & put(int16_t val)
    {
        char lsb, msb;
        lsb = (char)val;
        val >>= 8;
        msb = (char)val;
        put(lsb) && put(msb);
        return *this;
    }
    ~Ofstream() {}
};
int main()
{
    int16_t val = 0x1234;
    Ofstream ofile( "test");
    ofile.put(val);
}

在这里,我总是遇到段错误,那有什么问题呢?

最佳答案

您的 put() 函数调用自身而不是基类版本。所以你会得到无限递归,这会导致堆栈溢出。

替换

put(lsb) && put(msb);

std::ofstream::put(lsb) && std::ofstream::put(msb);

关于c++ - 如何重载 std::ofstream::put()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56816234/

相关文章:

C++ 从文件读取到 vector

c++ - ofstream 变量不能出现在 OpenMP firstprivate 中?

C++:在初始化列表中初始化对 ofstream 的引用

c++ - 使用迭代器遍历列表?

c++ - 虚拟继承在不需要或不使用时是否有成本?

c++ - 当重载函数作为参数涉及时,模板参数推导如何工作?

c++ - 为什么仅当我在 SDL2 中设置非零 alpha 大小时才获得 sRGB 帧缓冲区?

c++ - 常数可以优化掉吗

c++ - 将一组整数写入 std::ofstream 并能够读回它们

c++ - 在 C++ 中写入/读取文件