PDA

View Full Version : C++ overloading stream operator


TurkeyMaster77
12-16-2008, 08:45 AM
I'm simply having compiler error as I attempt to overload '<<.' The following code throws this error:
"error C2804: binary 'operator <<' has too many parameters MyObject.cpp"

Header file:
ostream& operator<< (ostream&, const MyObject&);

.cpp file:
ostream& operator<< (ostream& stream, const MyObject& obj)
{
stream << obj.code;

return stream;
}

Every search result I find has instructed me to follow almost this format exactly. I can't figure out what I'm doing wrong!

ralph l mayo
12-16-2008, 09:23 AM
You trimmed too much out to tell exactly what's going on, but my guess is that you're declaring the operator inside the class, which isn't what you want here. It should not be declared as a member but as an external function, granted access to the class internals with 'friend' if it's necessary.

See exactly how to do it here: http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.8

The whole FAQ lite is well worth a read.

edit: it occurs to me that you may have seen that but are only having problems when you try to divide the code between header and implementation, in which case:

// Header.h
class MyObject
{
// Only needed if code is not declared public, to grant the function access to it
// NB: this is not a member declaration
friend std::ostream& operator<<(std::ostream& stream, const MyObject& obj);
public:
MyObject(int code) : code(code) {}
private:
int code;
};

// Implementation.cpp
std::ostream& operator<< (std::ostream& stream, const MyObject& obj)
{
return stream << obj.code;
}