Why is this a mistake? "no suitable default constructor"

Someone gave me the following snippet of C ++ code to try - and now I have lost contact with them (its a long story). Anyway, it will not compile - I get an error message

error C2512: 'mstream': no ​​suitable default constructor

Can someone explain why and why this is needed.

class mstream : private ostream
{
  public:

  mstream& operator << (char *value)
  {
    printf ("[%s]\n", value);
    return *this;
  }
  mstream& operator << (int value)
  {
    printf ("[%u]\n", value);
    return *this;
  }

};
mstream g_mcout;

EDIT: Oh, missed that ...

ostream& mcout ()
{
  return g_mcout;
}
ostream& SgDebug ()
{
  return g_mcout;
}

FYI: the reason for this weird looking code is everything related to combining C ++ with the C program. The printf () file will actually be changed to my_printf (), which will do all kinds of custom things.

+3
source share
5 answers

ostream ; - mstream . ostream :

class mstream : private ostream
{
public:
    mstream() :
    ostream(/* whatever you want */)
    {}

    /* Maybe this is more appropriate:

    mstream(std::streambuf* pBuffer) :
    ostream(pBuffer)
    {}

    */

    // ...
};

. , , , .

+6

mstream ostream, typedef basic_ostream, char. mstream, , ostream, .

basic_ostream ( ), mstream . , :

explicit basic_ostream(
    basic_streambuf<_Elem, _Tr> *_Strbuf,
    bool _Isstd = false
);
basic_ostream(
    basic_ostream&& _Right
);

- , :

class mstreambuffer : public streambuf
{
public:
    mstreambuffer() : streambuf()
    {
    }
};

class mstream : private ostream
{
public:
    mstream(mstreambuffer* buff) : ostream(buff) {}
};

int main(void)
{
    mstreambuffer buff;
    mstream g_mcout(&buff);
    g_mcout << 32768;
    return 0;
}

mstreambuffer , streambuf .

, CRT (printf) ++ cout, . :

  mstream& operator << (int value)
  {
    std::cout << value << std::endl;
    return *this;
  }
+3

, , .

class mstream : private ostream
{
    public:
    mstream()
    {
    }
    ...
}

. http://www.cplusplus.com/reference/iostream/ostream/ostream/.

+1
source

Your parent class ( ostream) does not have a default constructor, so your class constructor mstreammust also manually create the parent element.

+1
source

std::ostream - typedef:

typedef basic_ostream<char, char_traits<char> > ostream;

Then std::basic_ostream<>there is no default constructor, only this:

explicit basic_ostream(basic_streambuf<Elem, Tr> *strbuf);

So, you need to explicitly call the base class constructor L

mstream(): ostream( pointer_to_some_implementation_of_streambuf ) { ... }
0
source

Source: https://habr.com/ru/post/1770917/


All Articles