Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading C++ Insertion Operator (<<)

I'm trying to write a class that overloads the insertion operator but in my header file I get the error.

Overloaded 'operator<<' must be a binary operator (has 3 parameters)

Here is my code:

.h file

ostream & operator<<(ostream & os, Domino dom);

.cpp file

ostream & operator<< (ostream & os, Domino dom) {
    return os << dom.toString();
}

I'm following a text book and this is what they use as an example but its not working for me.. Any suggestions?

like image 863
AFraser Avatar asked Feb 01 '12 04:02

AFraser


People also ask

Can insertion operator overloaded?

Input/Output Operators Overloading in C++ C++ is able to input and output the built-in data types using the stream extraction operator >> and the stream insertion operator <<. The stream insertion and stream extraction operators also can be overloaded to perform input and output for user-defined types like an object.

What is the insertion operator in C?

The insertion ( << ) operator, which is preprogrammed for all standard C++ data types, sends bytes to an output stream object. Insertion operators work with predefined "manipulators," which are elements that change the default format of integer arguments.

Can you overload an operator in C?

C does not support overloading of operators or functions. There's no way you can redefine < , <= , > , >= , == , or != to compare struct types directly.

Which operator is overloaded for CIN?

Notes: The relational operators ( == , != , > , < , >= , <= ), + , << , >> are overloaded as non-member functions, where the left operand could be a non- string object (such as C-string, cin , cout ); while = , [] , += are overloaded as member functions where the left operand must be a string object.


1 Answers

You probably put your operator<< inside a class declaration. That means it takes an extra hidden parameter (the this parameter). You need to put it outside of any class declaration.

like image 54
rob mayoff Avatar answered Sep 21 '22 10:09

rob mayoff