• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 501
  • Last Modified:

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
0
lwinkenb
Asked:
lwinkenb
  • 4
  • 2
1 Solution
 
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
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

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now