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
LVL 5
lwinkenbAsked:
Who is Participating?
 
ikeworkCommented:
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
0
 
ikeworkCommented:
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
0
 
lwinkenbAuthor Commented:
do all overloaded operators need to be declared as "friend", or just the stream ones?
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
ikeworkCommented:
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
0
 
lwinkenbAuthor Commented:
I understand now, thanks.  
0
 
ikeworkCommented:
you're welcome :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.