13

I have the following class(prototipe):

class Token
{
public:
    //members, etc.
    friend std::stringstream& operator<< (std::stringstream &out, Token &t);
};

And the operator is implemented like this:

std::stringstream & operator<< (std::stringstream &out, Token &t)
{
    out << t.getValue(); //class public method
    return out;
}

Now, I'm trying to use it like this:

std::stringstream out;
Token t;
//initialization, etc.

out << t;

And VS gives me error, saying that there is no match for << operator. What am I wrong in?

Dan Tumaykin
  • 1,213
  • 2
  • 17
  • 37
  • 1
    Welcome to SO. When you give code samples, please keep them a single, compilable piece of code. And *always* give the full compiler errors. – thiton Jan 12 '12 at 11:11

1 Answers1

16
std::stringstream & operator<< (std::stringstream &out, Token &t)

should be

std::ostream & operator<< (std::ostream &out, Token const &t)
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • 3
    just a question, why ostream, and not stringstream? because of stringstream is inheriting operator<< from ostream? also, is const mandatory? – Dan Tumaykin Jan 11 '12 at 18:08
  • @dtumaykin: `const` is not necessary, but it's good style. `ostream` is the class of output streams, which `ostringstream` and `stringstream` derive from. – Fred Foo Jan 11 '12 at 18:33
  • 2
    Observe the need for `friend` here: http://stackoverflow.com/questions/15777944/overloading-the-operator-error-c2804-binary-operator-has-too-many-param – villasv Nov 06 '15 at 05:49