I'm trying to apply some concepts of operator loading that I've learnt in the following C++ class.
#include<iostream>
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.