Hi,

I have made a class and have an overloaded ostream operator method in it... However it tells me:

"overloaded 'operator<<' must be a binary operator (has 3 parameters)."

Can someone tell me how to fix this? Thank you!

I have included some of my code:

class Element
{
private:
    list<Element*> _children;
    char* _tag;
    int _value;
public:
    ostream& operator<<(ostream& out, const Element& E); // (preordered traversal)
}

It's more typical to make this operator a friend, rather than a member function.

We also need to see the definition.

typically that wont work for operator overloading. do you imply shift operator or what?

As Moschops said, te stream insertion and extraction operators are usually implemented as free functions that is are friends of the class, rather than as members, but it would be useful to understand why this is the case. The reason you can't have it as a member operator is because in a class member function, the this pointer is an implicit argument to the function; in an operator, this means that the left side argument is assumed to be the object being operated on. However, for the stream out operator, you want the operator to act on the ostream reference as the left-hand argument, not the object being sent, so in order to get the desired result, the operator cannot be a member of the class it operates on.

In addition, you must explicitly scope the ostream& declarations, rather than relying on using namespace std;. You should never have a using namespace std directive in a header, in fact, for this a several other reasons having to do with namespace pollution, and using namespace std in general is a poor practice even in source files. The whole purpose of separating the standard library members into a separate namespace is to avoid collisions with user-defined functions, and wholesale application of using namespace std; undermines this. All references to the standard library functions should be explicitly scoped, strictly speaking, including such C-style functions as pow() or printf(), though most compilers let you cheat with the C library functions as a matter of convenience. Like with goto or the ternary conditional operator, it might be better if you deliberately forgot that the using directive exists, until you have a clearer understanding of when it is reasonable to apply it and why.

Grr, I meant to give a more detailed explanation of why the namespace for ostream& has to be explicitly scoped, but for the life of me I can't recall the explanation other than that it has to do with the declaration defaulting to the top-level anonymous namespace rather than the std namespace. Perhaps someone like mike_2000_17, Ancient Dragon or ddanbe could give a better explanation?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.