I came to a Problem where i cant print a returned object via cout.
I find it hard to describe so i wrote a very basic programm to show my problem.
The compiler says Type mismatch in operator<<.
The overloaded + Returns an Integer object, but why cant it be printed?
"Test.cpp"
#include <iostream>
#include "Integer.h"
using namespace std;
int main() {
Integer int1(5);
Integer int2(2);
cout << (int1 + int2) << endl; // Here it fails
cout << int2 << endl; // Works
return 0;
}
"Integer.cpp"
#include "Integer.h"
Integer::Integer(int integer) {
this->integer = integer;
}
int Integer::get_integer()
return integer;
}
Integer Integer::operator +(Integer& integer) {
return Integer(this->integer + integer.get_integer());
}
ostream& operator<<(ostream& output, Integer& integer) {
output << integer.get_integer();
return output;
}
"Integer.h"
#include <iostream>
using namespace std;
class Integer {
private:
int integer;
public:
Integer(int integer);
int get_integer();
Integer operator+(Integer& integer);
};
ostream& operator<<(ostream& output, Integer& integer);
Thanks in advance
It is illegal to bind a temporary object to a non-const reference:
cout << (int1 + int2) << endl; // The result of the '+' is temporary object.
To correct, change the argument of your operator<<
to a const Integer&
:
ostream& operator<<(ostream& output, const Integer& integer);
//^^^^^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With