Operator comparison operator == [closed]


I'm trying to make a comparison operator but I do not know how to approach it. The idea is that you can use the == operator to compare two objects of the same class, for example, I have this rational class:

class Racional{
     int numerador;
     int denominador;
    void setNumerador(int numerador);
    void setDenominador(int denominador);
    int getNumerador()const;
    int getDenominador()const;
    bool operator==(const NombreRacional& r)const; //(Supongo que el valor de retorno será un bool)

So now if I want to compare two rational numbers:

if(Racional1 == Racional2){

I can not find a way to do it, I'll stop what I tried:

bool Racional::operator==(const Racional& r)const {
    bool resultado = false;
    if(r.denominador == denominador && r.numerador == numerador){
    resultado = true;

    return resultado;

Edit: The operator is correct, the error came from before.

asked by Chariot 20.09.2018 в 00:05

1 answer


By custom I always implement the operator as a function (friend if necessary):

bool operator==(const Racional& lhs, const Racional& rhs)
    // Acorto los nombres de los métodos
    return lhs.num() == rhs.num() && lhs.den() == rhs.den();
answered by 20.09.2018 в 00:12