1

Im trying to overload the operators == and != but they don't seem to working as i intended they should.

It seems that for the first member comparison (num), the compiler checks the memory address instead of the value I assign to it. I know this because even if the values are all the same, it still sends back the message saying they "are NOT equal" which means they don't pass the if statement in the == function . How would I, make these functions just check their surface values.

Header:

bool operator == (const Rational &)const;
    bool operator != (const Rational &)const;

cpp:

Rational::Rational(int num, int den)
{
    setFrac(num, den);
}

void Rational::setFrac( int n, int d)
{
    num = new int;
    *num = n;

    den = d;
    if (den == 0)
    {
        cout << d << " is not a valid number." << endl;
        den = 1;
    }

    reduce ();
}


int Rational::getNumer()const
{
    return *num;
}

int Rational::getDenom() const
{
    return den;
}

bool Rational:: operator == (const Rational &rhs) const
{
    if (this->num == rhs.num && this->den == rhs.den)
    {
        cout << " is equal to ";
        return true;
    }
    else
       return operator != (rhs);
}

bool Rational:: operator != (const Rational &rhs) const
{
    if (this->num != rhs.num || this->den != rhs.den)
    {
        cout << " is NOT equal to ";
        return true;
    }
    else
        return operator == (rhs);
}

Main:

 cout << "Is f1 == f4?:" << endl;
    cout << "    f1"; if (f1 == f4) cout << "f4" << endl;

    cout << "Is f1 == f2?:" << endl;
    cout << "    f1"; if (f1 == f2) cout << "f2" << endl;

Thanks for the help.

jww
  • 97,681
  • 90
  • 411
  • 885

1 Answers1

4

Since "num" is stored as a pointer, you'll have to compare the values stored at that address, instead of comparing the pointer addresses. It looks like den is not a pointer, though, so you can just compare it like you're currently doing. In the example below, I've also rewritten your != operator in terms of the == operator for succinctness.

bool Rational:: operator == (const Rational &rhs) const
{
    assert(this->num && rhs.num);
    return *this->num == *rhs.num && this->den == rhs.den;
}

bool Rational:: operator != (const Rational &rhs) const
{
    return !(*this == rhs);
}
d3coy
  • 395
  • 1
  • 4