We help IT Professionals succeed at work.

overload << operator

lwinkenb
lwinkenb asked
on
Medium Priority
517 Views
Last Modified: 2010-04-01
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
Comment
Watch Question

CERTIFIED EXPERT
Commented:
hi lwinkenb,

you have to overload the global operator<< and make it a friend in your class, not implement it as a member of your class:


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);
};


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


hope it helps :)
ike

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT

Commented:
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

Author

Commented:
do all overloaded operators need to be declared as "friend", or just the stream ones?
CERTIFIED EXPERT

Commented:
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

Author

Commented:
I understand now, thanks.  
CERTIFIED EXPERT

Commented:
you're welcome :)
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.