C++ std::stringstream operator<< overloading

2020-03-11 04:45发布

问题:

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?

回答1:

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

should be

std::ostream & operator<< (std::ostream &out, Token const &t)