Order of operations of operators

I've been fiddling around with trying to do something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class str{string data; public:str(){data = "Hello World!\n";}
friend ostream &operator<<( ostream &, const str  & s);
str operator << (ostream & ostr)
    {
        ostr << data;
    }
};
str s;
cout << s << "Hallo Welt!" << endl;
ostream &operator<<( ostream &output, const str &s )
    {
        output << s.data;
        return output;
    } 


But i'm encountering some weird issues.
The cout statement is couting the initial value of s, as the s is the first thing encountered after cout <<.
Then its couting "Hallo Welt!".
I had wanted the Hallo Welt to be stored in s before the couting.
But if I try to force the order of operations the way I want with a ()
e.g. cout << (s << "Hello Welt");
it couts 1, the boolean equivalent of s << "Hello Welt" having been achieved.
How can I achieve this?

So far the best that I can come up with is:
1
2
3
4
5
6
7
    str operator = (const string & rhs)
    {
        data = rhs;
        //return data;
        return *this;
    }//declared in class str of course
cout << (s = "To be or not to be, that is the question.\n") << flush << endl; 


Thanks.
Last edited on
I'm unclear about what you're trying to do. And why?

<< has an expected behaviour. Changing it do something different is a very bad idea, as it would confuse people maintaining the code in the future.

And code should really do one thing at a time: store and then display.
closed account (DSLq5Di1)
wtf wrote:
So far the best that I can come up with ..
Replace = with << and that should function as you wanted, though I'm with andy on this one.. why?
Topic archived. No new replies allowed.