views:

166

answers:

3

Hello, everyone!

In a project I'm working on, I have a Score class, defined below in score.h. I am trying to overload it so, when a << operation is performed on it, _points + " " + _name is returned.

Here's what I tried to do:

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

Here are the errors returned:

1>c:\users\francisco\documents\feup\1a2s\prog\projecto3\projecto3\score.h(30) : error C2804: binary 'operator <<' has too many parameters

(This error appears 4 times, actually)

I managed to get it working by declaring the overload as a friend function:

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

And removing the Score:: from the function declaration in score.cpp (effectively not declaring it as a member).

Why does this work, yet the code describe above doesn't?

Thanks for your time!

EDIT

I deleted all mentions to the overload on the header file... yet I get the following (and only) error. binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion) How come my test, in main(), can't find the appropriate overload? (it's not the includes, I checked)

Below is the full score.h

///////////////////////////////////////////////////////////
//  Score.h
//  Implementation of the Class Score
//  Created on:      10-Mai-2010 11:43:56
//  Original author: Francisco
///////////////////////////////////////////////////////////

#ifndef SCORE_H_
#define SCORE_H_

#include <string>
#include <iostream>
#include <iostream>

using std::string;
using std::ostream;

class Score
{

public:
 Score(string name);
 Score();
 virtual ~Score();
 void addPoints(int n);
 string scoreGetName() const;
 int getPoints() const;
 void scoreSetName(string name);
 bool operator>(const Score right) const;

private:
 string _name;
 int _points;

};
#endif
+11  A: 

Binary operators can either be members of their left-hand argument's class or free functions. (Some operators, like assignment, must be members.) Since the stream operator's left-hand argument is a stream, they either have to be members of the stream class or free functions. The canonical way to implement operator<< for any type is this:

std::ostream& operator<<(std::ostream& os, const T& obj)
{
   // stream obj's data into os
   return os;
}

Note that it is not a member function. Also note that it takes the object to stream per const reference. That's because you don't want to copy the object in order to stream it and you don't want the streaming to alter it either.


Sometimes you want to stream objects whose internals are not accessible through their class' public interface, so the operator can't get at them. Then you have two choices: Either put a public member into the class which does the streaming

class T {
  public:
    void stream_to(std::ostream&) {os << obj.data_;}
  private:
    int data_;
};

and call that from the operator:

inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
   obj.stream_to(os);
   return os;
}

or make the operator a friend

class T {
  public:
    friend std::ostream& operator<<(std::ostream&, const T&);
  private:
    int data_;
};

so that it can access the class' private parts:

inline std::ostream& operator<<(std::ostream& os, const T& obj)
{
   os << obj.data_;
   return os;
}
sbi
Nice, complete answer.
Noah Roberts
Access the class' private parts - Rawr.J/K, thank you very much, yet one question remains:I deleted all mentions to the overload on the header file... yet I get the following (and only) error.`binary '<<' : no operator found which takes a right-hand operand of type 'Score' (or there is no acceptable conversion)`How come my test, in main(), can't find the appropriate overload? (it's not the includes).
Francisco P.
You should put the declaration of the `operator<<` right with the definition of your class: that is in the same header and in the same namespace. This way you won't forget to include it and you the compiler will be able to pick it up when looking for acceptable overloads.
Matthieu M.
How am I supposed to put it in the same namespace w/o declaring it as a member?
Francisco P.
`class T { }; ostream` Like that. You want it in the same namespace that the class itself exists in, not necessarily inside the class itself.
Dennis Zickefoose
@Francisco: That C++ allows only friends to touch your private parts is one of the oldest jokes in the community. (And I thus apologize to everyone else for having brought it up here.) The compiler needs a __declaration__ in order to allow you to call the operator. The linker later needs the (one) __definition.__ You best put operators and other free functions relating to a class into the same namespace as the class. This allows argument-dependent lookup to pick them up. See here http://stackoverflow.com/questions/1410563/1410632#1410632 for more details regarding this.
sbi
+2  A: 

Let's say you wanted to write an operator overload for + so you could add two Score objects to each other, and another so you could add an int to a Score, and a third so you could add a Score to an int. The ones where a Score is the first parameter can be member functions of Score. But the one where an int is the first parameter can't become member functions of int, right? To help you with that, you're allowed to write them as free functions. That is what is happening with this << operator, you can't add a member function to ostream so you write a free function. That's what it means when you take away the Score:: part.

Now why does it have to be a friend? It doesn't. You're only calling public methods (getPoints and scoreGetName). You see lots of friend operators because they like to talk directly to the private variables. It's ok by me to do that, because they are written and maintained by the person maintaing the class. Just don't get the friend part muddled up with the member-function-vs-free-function part.

Kate Gregory
Thanks for the extra input!
Francisco P.
+3  A: 

You're compilation errors when operator<< is a member function in the example because you're creating an operator<< that takes a Score as the first parameter (the object the method's being called on), and then giving it an extra parameter at the end.

When you're calling a binary operator that's declared as a member function, the left side of the expression is the object the method's being called on. e.g. a + b might works like this:

A a;
B b

a.operator+(b)

It's typically preferable to use non-member binary operators (and in some cases -- e.g. operator<<for ostream is the only way to do it. In that case, a + b might work like this:

A a;
B b

operator+(a, b);

Here's a full example showing both ways of doing it; main() will output '55' three times:

#include <iostream>

struct B
{
    B(int b) : value(b) {}
    int value;
};


struct A
{
    A(int a) : value(a) {}
    int value;

    int operator+(const B& b) 
    {
        return this->value + b.value;
    }
};

int operator+(const A& a, const B& b)
{
    return a.value + b.value;
}

int main(int argc, char** argv)
{
    A a(22);
    B b(33);

    std::cout << a + b << std::endl;
    std::cout << operator+(a, b) << std::endl;
    std::cout << a.operator+(b) << std::endl;

    return 0;
}
pkh