views:

58

answers:

2

Hello everyone.

I edited a post of mine with this question, yet got no answers.

I overloaded << for a class, Score (defined in score.h), in score.cpp.

ostream& operator<< (ostream & os, const Score & right)
{
 os << right.getPoints() << " " << right.scoreGetName();
 return os;
}

(getPoints fetches an int attribute, getName a string one)

I get this compiling error for a test in main(), contained in main.cpp

binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion)

How come the compiler doesn't 'recognize' that overload as valid? (includes are proper)

Thanks for your time.

EDIT:

As requested, code causing the error:

cout << ":::::\n" << jogador.getScore() << endl;

jogador is a Player object, which contains a Score one. getScore returns that attribute.

+4  A: 

Perhaps you didn't declare your operator<< in score.h? It should normally contain something like:

ostream& operator<< (ostream & os, const Score & right);

Edit: More accurately, that should be:

std::ostream &operator<<(std::ostream &os, const Score &right);

You definitely should not have a using namespace std; in a header, so you need the std:: for it to work correctly.

Jerry Coffin
That won't work, because the left side parameter is not of type `Score`. At least, another question on here made me think that.
Francisco P.
@Francisco P. - The compiler is complaining about an rvalue, not an lvalue. Ie, it's worried about the right hand parameter.
sheepsimulator
Don't put this one line in the class declaration, put it *after* the class declaration.
dash-tom-bang
@dash-tom-bang - I see, thank you very much!
Francisco P.
Herb Sutter: "operator<< can't be a member because it requires a stream as the left-hand argument" http://www.gotw.ca/publications/mill02.htm
sheepsimulator
Jerry Coffin
+2  A: 

Try declaring operator<< as a friend function in your class:

struct Score
{
  friend ostream& operator<<(ostream& output, const Score& right);
};

This will allow your Score structure to fit nicely into printing statements:

Score my_score;
cout << my_score << endl;

When in doubt, check the C++ FAQ.

Thomas Matthews
I was looking for a different way to do that. Even though it works, there is no reason I need to friend operator<<. I like the accepted answer's suggestion more. But thanks for your time/effort in helping me.
Francisco P.
This answer is helpful if Score::getPoints() and/or Score::scoreGetName() are private. But I don't think you need the struct Score around it, by the Interface Principle.
sheepsimulator