../src/blockbusta.cpp: In function ‘int main()’:
../src/blockbusta.cpp:78: error: no match for ‘operator<<’ 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.
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.
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.
@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...