ostringstream return value

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • CPP freshman
    New Member
    • May 2012
    • 15

    ostringstream return value

    I am confused:

    This works fine:
    ostringstream& print(ostringst ream&s){
    s<<"abcd";
    return s;
    }

    This produces an error:
    ostringstream& print(ostringst ream&s){
    return s<<"abcd";
    }
  • CPP freshman
    New Member
    • May 2012
    • 15

    #2
    Replaced ostringstream with ostream, and it worked.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      operator<< returns an ostream&. Your function returns an ostringstream&. For this to work the compiler needs to convert an ostream& to an ostringstream& and that requires a conversion constructor in the ostream class. There isn't one so you get this error.

      However you can write your own operator<< to do what you want. The compiler will call it and that will bypass the need of a conversion constructor:
      Code:
      ostringstream& operator<<(ostringstream& ss,  const char* str)
      {
          ss << str;
      	return ss;
      }
      Just make sure this function (or its prototype) appears before your print function.

      Comment

      Working...