# Doubt with Operator Overload Exercise + and -

2

The exercise asks me to implement the addition and subtraction each with a single member method. And you have to be able to execute the following code:

``````        int main()
{
Punto p(12.34,-56.78);
Punto r,s;
s=78+p;
r=78-p;
cout<<"1. punto p= ("<<p.getX()<<";"<<p.getY()<<")"<<endl;
cout<<"2. punto 78+p: s= ("<<s.getX()<<";"<<s.getY()<<")"<<endl;
cout<<"3. punto 78-p: r= ("<<r.getX()<<";"<<r.getY()<<")"<<endl;
r=p+s-45;
cout<<"4. punto p+s-45: r= ("<<r.getX()<<";"<<r.getY()<<")"<<endl;
}
``````

How can the operator overload be done so that the operation can be done in both ways ( `int+Punto` and `Punto+int` ) with a single method?

asked by Fokker 15.04.2018 в 21:05
source

1

The exercise asks me to implement the addition and subtraction of each one with a single member method.

It is not the same `int + Punto` as `Punto + int` . These cases are going to be treated by independent functions. In the case of the member function, the operator, expressed explicitly, would remain as follows:

``````Punto Punto::operator+(this,int);
``````

It's easy to see that this function does not work for the case `int + Punto` since you can not convert an integer in a point and a point in an integer ... To deal with the case `int + Punto` you need, as we have said, a friend function:

``````class Punto
{
friend Punto operator+(int,Punto const& punto); // funcion amiga

// ...

Punto operator+(int valor) const; // funcion miembro
};

Punto operator+(int valor, Punto const& punto)
{
return punto + valor;
}

Punto Punto::operator+(int valor) const
{ /* ... */ }
``````

Note that the function is not a member (and if you try to make it a member you will have a nice compilation error).