overloading

I'm having trouble overloading the output operator <<

When I try and compile my code it says there are too many perameters for the operator.

My code is something like this:

[code]
ostream& operator <<(ostream&, myclass&);
[/code]

I can't remember the code exactly as I'm on a different computer to my own but I think it was similar to the above (I got it from C++ Primer Plus).

Can anyone tell me what's wrong or give me an example that works?

J

Comments

  • : I'm having trouble overloading the output operator <<
    :
    : When I try and compile my code it says there are too many perameters for the operator.
    :
    : My code is something like this:
    :
    : [code]
    : ostream& operator <<(ostream&, myclass&);
    : [/code]
    :
    : I can't remember the code exactly as I'm on a different computer to my own but I think it was similar to the above (I got it from C++ Primer Plus).
    :
    : Can anyone tell me what's wrong or give me an example that works?
    :
    : J
    :


    make it a frend membor of the class
    [code]
    class myclass
    {
    public:
    friend ostream& operator <<(ostream&, myclass&);
    ...
    };
    [/code]


  • : make it a frend membor of the class
    : [code]
    : class myclass
    : {
    : public:
    : friend ostream& operator <<(ostream&, myclass&);
    : ...
    : };
    : [/code]
    :
    :
    :
    I've tried making it a friend and now it has a problem with my implementation (it says that << isn't a member function of myclass).

    Here's the implementation:
    [code]
    ostream& myclass::operator << (ostream &_out, const myclass &_rhs)
    {
    _out << _rhs.name;
    return _out;
    }[/code]
  • :
    : Here's the implementation:
    : [code]
    : ostream& myclass::operator << (ostream &_out, const myclass &_rhs)
    : {
    : _out << _rhs.name;
    : return _out;
    : }[/code]
    :


    your compiler is right -- friends are NOT members of the class, but members of global namespace or some other class. I didn't compile it, but this will probably work. just remove "myclass::"
    [code]
    ostream& operator << (ostream &_out, const myclass &_rhs)
    {
    _out << _rhs.name;
    return _out;
    }[/code]


Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories