简体   繁体   中英

How to call operator<< on “this” in a descendant of std::stringstream?

class mystream : public std::stringstream
{
public:
    void write_something()
    {
        this << "something";
    }
};

This results in the following two compile errors on VC++10:

error C2297: '<<' : illegal, right operand has type 'const char [10]'
error C2296: '<<' : illegal, left operand has type 'mystream *const '

Judging from the second one, this is because what this points at can't be changed, but the << operator does (or at least is declared as if it does). Correct?

Is there some other way I can still use the << and >> operators on this ?

mystream *const means that this is a constant pointer to a non-constant object. The problem is that you're trying to stream-insert into a pointer -- you must insert into a stream. Try the following.

*this << "something";

The destructor of an stringstream (actually a basic_stringstream<char> ) is not virtual, and as all classes from the C++ SL, you're not really supposed to derive from them...

Depending on what exactly you want to do, I will tell you to prefer composition to inheritance, and maybe create your own templated << and >> operators that will use your underlying stream. Or maybe it is wiser not to use a stringstream as a member.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM