I'm having a really werid issue with overloading the insertion operator (<<).
Here's my code snippet:

    class instream
    {
        void operator<< (instream&, char[]);
    };

Visual Studio keeps telling me I have "too many arguments for binary operator <<". I don't see the problem here. Is there something obvious I'm missing?

Dani AI

Generated

The Visual Studio error "too many arguments for binary operator <<" usually means the operator was declared with the wrong form. A binary operator can be either a member (the left operand is the object itself) or a non-member (a free function that takes both operands). Both are valid — choose the form that matches which object should appear on the left of <<.

Here are two correct patterns you can use (different from the snippets already in the thread):

class MyStream {
public:
MyStream& operator<<(const std::string& s) {
writeImpl(s);
return *this; // enable chaining: ms << "a" << "b";
}
private:
void writeImpl(const std::string&);
}

class MyStream {
friend MyStream& operator<<(MyStream& ms, const std::string& s);
private:
void writeImpl(const std::string&);
};

MyStream& operator<<(MyStream& ms, const std::string& s) {
ms.writeImpl(s);
return ms;
}

Practical tips: prefer const std::string& (or const char*) over a raw char[] parameter, and return a non-const reference to allow chaining. If you want the standard std::ostream << obj syntax, implement a non-member std::ostream& operator<<(std::ostream&, const T&). If your class is meant for input (named "instream"), consider implementing operator>> instead of operator<<. For the language rules and canonical examples see the operator-overloading and stream insertion pages on cppreference: Operators (C++) and basic_ostream::operator<<.

This expands on suggestions from and by showing proper signatures, return-value guidance, and small design notes to avoid the compiler error and get chaining and const-correctness right.

Recommended Answers

All 2 Replies

Alright. So, operators of this type HAVE to be friend functons. Makes sense. I think...

Since this is a member of the class (not a static method), you can leave off the first argument and in the body of the method do this:

void instream::operator<<(char[] data)
{
    this->someOutputFunction(data);
}

Just an aside, if this is an input stream, why are you writing an output operator?

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.