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
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
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
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
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
ASKER
I understand now, thanks.
you're welcome :)
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