How to combine overload operators << and + ?

I dont know if it is possible

I want to have a class to store strings.
For example I have :
1
2
   double a;   std::string b,
         a=15.44       b="hello"


And I'd want to write

1
2
3
  myclass += a;     // Myclass would store "15.44"
  myclass << a+b;   // Myclass would store "15.44hello"
  myclass = a+b;    // Myclass would store "15.44hello" 


Now I have the << operator well write and I can do :
myclass<<a<<b
(Using stringstream to store data)
And it works fine.

But I' like to simply write '+'.
I dont know how to write the body of funtions to use '+' operator . Now I have :

1
2
W_debug & W_debug::operator + (const char data) {  os<<data;     return *this;}
W_debug & W_debug::operator + (double data) { os<<data;     return *this;}


W_debug()<<"tam pixels "+doublescalaX;
Compiler tells me :
invalid operands of types 'const char [15]' and 'double' to binary 'operator+'

or
W_debug()<<"tamaño pixels "+pix_xx + " " +pix_yy+"";

invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'

I'm confused. Maybe what I want is not possible ?
Any help ? thanks.
Last edited on
The keyword is operator precedence here.

I'm confused. Maybe what I want is not possible ?


It's possible, but it isn't really helpful.
For me is very useful.

If I write :
W_debug()<<"tamaño pixels "<<pix_xx <<" "<<+pix_yy<<"";
I write << (two times) instead of '+' 1 character.
W_debug()<<"tamaño pixels "+pix_xx + " " +pix_yy+"";
Ok, this is not a existential need but only by curiosity... I'd want to write the right code.

( What is operator precedence in this problem ? ..... )

Thanks
Last edited on
+ has higher precedence than << so, myclass << a+b; is the same as myclass << (a+b);.
myclass << a << b; is instead equivalent to ( myclass << a ) << b;.

If you want a long chain of operators you should stick to one
you can use + instead of << but it wouldn't be a good choice since you don't expect a + to modify an object
Topic archived. No new replies allowed.