繁体   English   中英

重载运算符==&!=

[英]Overloading operators == & !=

我试图重载运算符==和!=,但它们似乎没有按照我的预期工作。

似乎对于第一个成员比较(num),编译器将检查内存地址,而不是我分配给它的值。 我知道这一点,因为即使这些值都相同,它仍然会发回消息说它们“不相等”,这意味着它们不会在==函数中传递if语句。 我将如何使这些功能仅检查其表面值。

标头:

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);
}

主要:

 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;

谢谢您的帮助。

由于“ num”存储为指针,因此您必须比较存储在该地址的值,而不是比较指针地址。 不过,看起来den不是一个指针,因此您可以像正在执行的操作一样比较它。 在下面的示例中,为了简洁起见,我还用==运算符重写了!=运算符。

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM