I'm trying to overload different operators, such as >, =, -=, >=, but for some reason I keep getting same error, expression must be bool type (or be convertable to bool)
Example
Money operator>=(const Money& lhs, const Money& rhs)
{
return lhs.pounds, rhs.pounds >= lhs.pence, rhs.pence;
}
I've also tried
Money operator>=(const Money& lhs, const Money& rhs)
{
return std::tie(lhs.pounds, rhs.pounds) < (lhs.pence, rhs.pence);
}
I'm trying to compare objects that inherit the object that I'm trying to compare, for example.
accounts[paramB] is an account object inside std::vector<Account*>. The Accounts class inherits Money class, and has a Money balance; member;
Account::Money getBalance(); { return 0; }
Savings::Money getBalance { return (balance.pounds, balance.pence) }
Money amount;
if(accounts[paramB]->getBalane() > amount)
...
Is there a way I can compare the same object without have to specify pounds and pence seperately?
if(accounts[paramB]->getBalane().pounds > amount.pounds && accounts[paramB]>getBalance().pence > amount.pence)
...
CodePudding user response:
The return type of comparisons must be bool and cannot be Money. This is a simple logic expression.
CodePudding user response:
I'm not sure what it is you are doing here:
Money operator>=(const Money& lhs, const Money& rhs)
{
return lhs.pounds, rhs.pounds >= lhs.pence, rhs.pence;
}
This expression looks strange to me, and I'm not sure if it is even valid or not. When you overload this kind of comparison operator, it must return either true or false: a bool type. What if you did something like this?
bool operator>=(const Money& lhs, const Money& rhs)
{
return (lhs.pounds >= rhs.pounds) && (lhs.pence >= rhs.pence);
}
I hope I'm not being presumptuous on what it is you're trying to do. This example uses the "and" binary logic operator and compares the pounds field and the pence field. You could also use the binary "or".
bool operator>=(const Money& lhs, const Money& rhs)
{
return (lhs.pounds >= rhs.pounds) || (lhs.pence >= rhs.pence);
}
Either way, this type of operator should return bool and not Money.
CodePudding user response:
return lhs.pounds, rhs.pounds >= lhs.pence, rhs.pence;
is parsed as
return lhs.pounds, (rhs.pounds >= lhs.pence), rhs.pence;
so is equivalent to
return rhs.pence;
std::tie is the way to go (in general case), but you don't use it correctly (and your return type is wrong). It should be
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;
}
