Link to home
Create AccountLog in
Avatar of lwinkenb
lwinkenb

asked on

overload << operator

I get an error trying to overload <<

class Test
{
private:
      int value;

public:
      Test();
      Test(int value);

      ostream& operator <<(ostream &os,const Test &obj);
};

ostream& Test::operator << (ostream &os,const Test &obj)
{
    os << obj.value;
    return os;
}

my error:
error C2804: binary 'operator <<' has too many parameters
ASKER CERTIFIED SOLUTION
Avatar of ikework
ikework
Flag of Germany image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
oops forgot to remove your old member-operator in the class-definition, must be:

class Test
{
    friend ostream& operator<< (ostream &os,const Test &obj);

private:
     int value;

public:
     Test();
     Test(int value);
};


ostream& operator<< (ostream &os,const Test &obj)
{
    os << obj.value;
    return os;
}


ike
Avatar of lwinkenb
lwinkenb

ASKER

do all overloaded operators need to be declared as "friend", or just the stream ones?
only if they access a private/protected variable of the class, if you put a publuc accessor-method to the class, then you dont need it.

this way you dont need it:

class Test
{
private:
     int value;

public:
     Test();
     Test(int value);

     // now the operator uses this ...
     int GetValue() { return value; }
};

ostream& operator<< (ostream &os,const Test &obj)
{
    os << obj.GetValue();
    return os;
}


ike
I understand now, thanks.  
you're welcome :)