重载具有多个成员字段的运算符

Overloading operators with multiple member fields

我正在尝试重载不同的运算符,例如 >, +=, -=, >=,但出于某种原因我不断收到相同的错误,表达式必须是 bool 类型(或可转换为 bool)

例子

Money operator>=(const Money& lhs, const Money& rhs)
{
    return lhs.pounds, rhs.pounds >= lhs.pence, rhs.pence;
}

我也试过了

Money operator>=(const Money& lhs, const Money& rhs)
{
    return std::tie(lhs.pounds, rhs.pounds) < (lhs.pence, rhs.pence);
}

例如,我正在尝试比较继承了我正在尝试比较的对象的对象。

accounts[paramB]std::vector<Account*> 中的一个帐户对象。 Accountsclass继承了Moneyclass,并且有一个Money balance;成员;

Account::Money getBalance(); { return 0; }
Savings::Money getBalance { return (balance.pounds, balance.pence) }

Money amount;

if(accounts[paramB]->getBalane() > amount)
    ...

有没有一种方法可以比较同一个对象而不必分别指定英镑和便士?

if(accounts[paramB]->getBalane().pounds > amount.pounds && accounts[paramB]>getBalance().pence > amount.pence)
...

return 类型的比较必须是 bool,不能是 Money。这是一个简单的逻辑表达式。

我不确定你在这里做什么:

Money operator>=(const Money& lhs, const Money& rhs)
{
    return lhs.pounds, rhs.pounds >= lhs.pence, rhs.pence;
}

我觉得这个表达式很奇怪,我不确定它是否有效。当您重载这种比较运算符时,它必须 return truefalse:bool 类型。如果你做了这样的事情怎么办?

bool operator>=(const Money& lhs, const Money& rhs)
{
    return (lhs.pounds >= rhs.pounds) && (lhs.pence >= rhs.pence);
}

我希望我对您的尝试没有冒昧。此示例使用“and”二元逻辑运算符并比较 pounds 字段和 pence 字段。您也可以使用二进制“或”。

bool operator>=(const Money& lhs, const Money& rhs)
{
    return (lhs.pounds >= rhs.pounds) || (lhs.pence >= rhs.pence);
}

无论如何,这种类型的运算符应该 return bool 而不是 Money.

return lhs.pounds, rhs.pounds >= lhs.pence, rhs.pence;

被解析为

return lhs.pounds, (rhs.pounds >= lhs.pence), rhs.pence;

所以等同于

return rhs.pence;

std::tie 是正确的方法(在一般情况下),但您没有正确使用它(并且您的 return 类型错误)。应该是

bool operator < (const Money& lhs, const Money& rhs)
{
    return std::tie(lhs.pounds, lhs.pence) < (rhs.pounds, rhs.pence);
    // Might be more appropriate in your case
    // return (100 * lhs.pounds + lhs.pence) < (100 * rhs.pounds + rhs.pence);
    // or, with appropriate helper function
    // return to_pence(lhs) < to_pence(rhs);
}

bool operator > (const Money& lhs, const Money& rhs)
{
    return rhs < lhs;
}

bool operator <= (const Money& lhs, const Money& rhs)
{
    return !(rhs < lhs);
}

bool operator >= (const Money& lhs, const Money& rhs)
{
    return rhs <= lhs;
}