Reputation: 3287
I have the following operator-overloading prototypes:
ostream& operator<<(ostream & outputstream, my_arr& arr)
my_arr operator+(const my_arr& left, const my_arr& right)
I call:
cout << (arr1 + arr2);
This gives me the following compiler error:
error: no match for ‘operator<<’ in ‘std::cout << operator+(const my_array&, const my_array&)((*(const my_array*)(& y)))’
This goes away if I change the signature of << to the following:
ostream& operator<<(ostream & outputstream, const my_arr& arr)
I might be missing something basic here, but why does this happen? Thanks for your help.
Upvotes: 3
Views: 119
Reputation: 45410
Because you have a typo in operator+
also you need to pass const my_arr
to operator
my_array operator+(const my_arr& left, const my_arr& right)
^^^^ should be my_arr ^^^ need to be const
Or you have to overload operator<<
for my_array
ostream& operator<<(ostream & outputstream, my_arr& arr)
Otherwise the code just compiles and runs OK: sample link
Upvotes: 1
Reputation: 26040
As has been mentioned, the result of this is a temporary (an rvalue). You can also provide an overload of your output operation which has the form:
ostream& operator<<(ostream& outputstream, my_arr&& arr);
which cout << (arr1 + arr2);
will then utilize.
Upvotes: 2
Reputation: 15154
The problem is that when passing as reference, you cannot pass "temporary" (rvalue) objects such as the result of an addition. When passing a const reference, C++ rules allow passing temporaries because it's guaranteed they won't be written to.
Upvotes: 4