C ++ | cout, back to print Object

I came up with a problem when I cannot print the returned object via cout.

It's hard for me to describe, so I wrote a very basic program to show my problem.

The compiler talks about type mismatch in the <operator

Overloaded + Returns an Integer object, but why can't 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); 

Thank you in advance

+6
source share
1 answer

You cannot bind a temporary object to a non-constant reference:

 cout << (int1 + int2) << endl; // The result of the '+' is temporary object. 

To fix, change the argument of your operator<< to const Integer& :

 ostream& operator<<(ostream& output, const Integer& integer); //^^^^^ 
+9
source

Source: https://habr.com/ru/post/959424/


All Articles