[SOLVED] Overload operator<< : no match for ‘operator<<’

Hello,

I am trying to overload the << operator in order to write a "Printer" class like the class of std::cout.

header file:
1
2
3
4
5
6
7
class Printer {
public:
	Printer();
	virtual ~Printer();

	void operator<< (int& val);
};

cpp file:
1
2
3
4
void Printer::operator<< (int& val)
{
	cout << val;
}


But the compiler (g++) says
1
2
3
../src/blockbusta.cpp: In function ‘int main()’:
../src/blockbusta.cpp:78: error: no match foroperator<<’ in ‘p << 14’
../src/Printer.h:20: note: candidates are: void Printer::operator<<(int&)

when I use the class this way in the main program:
Printer p;
p << 14;

And actually I'd like to define the << operator as a static method because there is no reason for instantiating Printer (static void operator<< (int& val);). But this gives me a different compiler error.

What am I doing wrong? I would be glad about some hints.

Kind regards,
Chris
Last edited on
You're passing by reference (int&), which means you need an object/variable to refer to.

'14' is an integer literal, it is not a variable, so you cannot pass it by reference. Just pass the integer by value (int val instead of int& val).

If you want to make it static, you won't be able to use the << operator without instantiating a Printer object unless you use really weird syntax:

1
2
3
4
5
6
7
// non-static (can also be called this way if static)
//  requires you have an instance of Printer ('p' here)
Printer p;
p << 15;

// static way... no Printer instance:
Printer::operator << (15);


As you can see, the static way isn't very intuitive, and kind of defeats the point of having an overloaded operator.
Last edited on
With 'int &' you can only pass actual variables, since it is implied that the function will try to modify the parameter. I think it should work if you change the type to 'const int &'. 'int' will work, too.

EDIT: O_o
Last edited on
er.. yeah I guess const int& would work too. ^^. Though passing an int by const reference seems a little silly to me.
@Disch, helios: Thank you very much for your help. I did not think of this. Now it works! :-)

@Disch: The static call you suggest is really weird. But since the class itself doesn't compile with a static operator, I think it will not compile anyway...

Kind regards and best wishes,
Chris
Topic archived. No new replies allowed.