Thursday, 25 January 2018

c++ - Operator overloading code compilation error, template argument deduction/substitution failure



I'm trying to apply some concepts of operator loading that I've learnt in the following C++ class.




#include
using namespace std;

class Point
{
private:
int x, y;
public:
Point(int, int);

Point operator+(const Point&);
friend istream& operator>>(istream& in, Point&);
friend ostream& operator<<(ostream& out, Point&);
Point operator=(const Point&);
};

Point::Point(int x = 0, int y = 0)
:x(x), y(y){}

Point Point::operator+(const Point& p)

{
int r1, r2;
r1 = x + p.x;
r2 = y + p.y;
return Point(r1, r2);
}

Point Point::operator=(const Point& p)
{
this->x = p.x;

this->y = p.y;
return *this;
}

istream& operator>>(istream& in, Point& p)
{
char openParenthesis, closeParenthesis, comma;
cout << "Enter data in the format (1,2): ";
in >> openParenthesis >> p.x >> comma >> p.y >> closeParenthesis;
return in;

}

ostream& operator<<(ostream& out, Point& p)
{
out << "(" << p.x << "," << p.y << ")";
return out;
}

int main()
{

Point a, b;
cin >> a >> b;

cout << "a + b is: " << a + b << endl;
return 0;
}


The code compiles and runs fine on Visual Studio. But when I try to compile it on Linux with gcc, it throws a long list of errors along the lines of:





In file included from /usr/include/c++/4.8/iostream:39:0,
from optr_overload.cpp:1: /usr/include/c++/4.8/ostream:471:5: note: template std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, _CharT)
operator<<(basic_ostream<_CharT, _Traits>& __out, _CharT __c)
^ /usr/include/c++/4.8/ostream:471:5: note: template argument deduction/substitution failed: optr_overload.cpp:53:30: note:
deduced conflicting types for parameter ‘_CharT’ (‘char’ and ‘Point’)
cout << "a + b is: " << a + b << endl;




I understand that the problem lies with the line where I passed "a + b" to the overloaded binary stream insertion operator which only receives reference to one Point object as the argument. But I've no idea how to fix the code other than assigning "a + b" to a third object and pass that single object as the argument to "<<". Could someone explain to me what exactly needs to be done in order for gcc to compile my code, preferably without involving the use of an extra placeholder object.


Answer




The value computed with a + b is a temporary object and therefore cannot be passed as a Point& to operator<<; the language only allows temporaries to be passed as const Point& instead. Just change he declaration of the output operator to accept a const Point&.



Allowing passing a temporary result as a non-const reference was a known bug in old versions of VC++.


No comments:

Post a Comment

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...