I am overloading the + operator externally. It is obvious that if I put:
Fraccion operator+ (const Fraccion& r1, const Fraccion& r2)
{
Fraccion res;
res.numerador = r1.obtenerNum() + r2.obtenerNum();
res.denominador = r1.obtenerDen() + r2.obtenerDen();
return res;
}
res.numerador
and res.denominador
they are not accessible since they are private members and could only be called via a public function that returns them, but if I use this:
Fraccion operator+ (const Fraccion& r1, const Fraccion& r2)
{
Fraccion res;
res.obtenerNum() = r1.obtenerNum() + r2.obtenerNum();
res.obtenerDen() = r1.obtenerNum() + r2.obtenerDen();
return res;
}
The compiler tells me that it is not assignable. It is clear that if I do the same overloading as a member function, it would be valid (the first overloaded function that I give you with members res.numerador
). But how should I put those variables so that they can access a value with that external overloaded function?
Thank you!
I attach the Fraction class (invented by me):
class Fraccion
{
public:
Fraccion(float n=0, float d=0) : numerador(n), denominador(d) {}
//Operador = OBLIGATORIA como función interna a la clase
Fraccion& operator=(const Fraccion& frac);
Fraccion& operator-(const Fraccion& frac2);
void mostrarFraccion() const;
void rellenarFraccion();
float obtenerNum() const { return numerador; }
float obtenerDen() const { return denominador; }
private:
float numerador;
float denominador;
};
Make your function a friend of your class:
By declaring
friend
it , you allow the function or class to access the membersprivate
andpublic
.And it is logical, if we look at the implementation:
We see that both
obtenerNum
returnobtenerDen
a VLD (right-hand side value RValue ). VLDs are a category of data that are expected to always be on the right of an operator and therefore cannot be used on the left of an operator (see this thread for more details).You could modify
obtenerNum
yobtenerDen
to return a VLI (left-hand side value):But you will need the constant and non-constant versions, it's a common practice (note the operator
at
)std::vector
.In this way your free operator is already functional:
But this code is rather confusing, take advantage of the fact that you have a constructor that receives numerator and denominator to construct your object
Fraccion
at return time and take advantage of return value optimization :The code is much simpler this way. Sure you can also use a function like Trauma
friend
suggests .