Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ | cout, Print returned Object

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

like image 872
Pius Friesch Avatar asked Dec 05 '13 21:12

Pius Friesch


1 Answers

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);
                                   //^^^^^
like image 197
hmjd Avatar answered Sep 22 '22 14:09

hmjd