How to overload std::ofstream::put()?

Nico Schumann

I want to write int16_t values to file.

Therefore I tried to overload the std::ofstream::put() method.

#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);
}

At this I always get a Segmentation fault, so what's wrong with?

Sid S

Your put() function calls itself rather than the base class version. So you get infinite recursion, which leads to stack overflow.

Replace

put(lsb) && put(msb);

with

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

Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.

En caso de infracción, por favor [email protected] Eliminar

Editado en
0

Déjame decir algunas palabras

0Comentarios
Iniciar sesiónRevisión de participación posterior

Artículos relacionados

¿Cómo sobrecargar std :: ofstream :: put ()?

SFML: How to overload Packet operator >> with a std::vector?

std :: ofstream странное поведение при записи целых чисел на границе байта от 256

ofstream.put (); no escribo ints?

Problema de klocwork para std :: ofstream open

Error handling in std::ofstream while writing data

¿No podemos administrar std :: map <string, ofstream>?

std :: ofstream no acepta const char * para << operador

Why no std::string overload for std::to_string

Есть ли способ сохранить снимок экрана с помощью ofstream?

std :: ofstream no puede escribir std :: string en el archivo

Cómo cambiar entre std :: ofstream y std :: cerr

Copie el contenido de std :: ofstream en un std :: string

how to use std::num_put for custom pointer output formatting?

How to parse a string created by std::put_time("%x") on Windows?

How to overload convert

std :: ofstream n'écrit pas dans le fichier

Usando el objeto auto_ptr <std :: ofstream>

¿Por qué puedo usar `operator <<` en objetos temporales std :: ofstream?

¿Cómo almacenar argumentos variadic de plantilla en std :: ofstream?

Por qué no std :: string overload para std :: to_string

how to overload an assignment operator in swift

How to select a specific overload of a method?

Python: How to overload operator with ast

How to iterate a class that overload the operator[]?

how to resolve overload errors in reactjs

no hay función coincidente para llamar a `std :: basic_ofstream <char, std :: char_traits <char>> :: basic_ofstream (std :: string &) '

std :: ofstream with std :: ate 끝에서 열리지 않음

Why does std::ofstream truncate without std::ios_base::trunc?

TOP Lista

CalienteEtiquetas

Archivo