C++ | cout, Print returned Object
Asked Answered
B

1

7

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

Brodie answered 5/12, 2013 at 21:27 Comment(1)
The signature of your operator << function is the problem.Omegaomelet
S
12

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);
                                   //^^^^^
Snell answered 5/12, 2013 at 21:30 Comment(4)
Interesting... I just plopped the original code into VS2012 and it worked exactly as written. Any idea why?Preeminent
Which will require adding some const to appropriate places in class Integer as well.Colic
@aardvarkk, vs has non-standard extensions, this is one of them (there is a flag that disables them but I can't remember it of the top of my head).Snell
@Snell Don't sweat it, this is one of the "extensions" that the flag doesn't affect anyway.Marieann

© 2022 - 2024 — McMap. All rights reserved.