重载操作符类型错误

Overloaded Operator Type Error

本文关键字:错误 类型 操作符 重载      更新时间:2023-10-16

我创建了一个Money类,它使用以下函数将Money转换为其值的百分比。我试图创建一个重载操作符来实现同样的目标,但是我在下面的重载操作符中为scaledCents获得Error: Expression must have integral or unscoped enum type;它们在其他方面是相同的。如何修正这一点?提前谢谢。

Money Money::percent(const Money& amount, double percentage) const {
    int amountToCents = amount.getCents() + amount.getDollars() * 100;
    double pScaledMoney = amountToCents * percentage;
    int scaledDollars = abs((round(fabs(pScaledMoney / 100))) / 100);
    int scaledCents = abs((round(fabs(pScaledMoney / 100))) % 100);
    if (pScaledMoney < 0) {
        scaledDollars = -scaledDollars;
        scaledCents = -scaledCents;
    }
    return Money(scaledDollars, scaledCents);
}

重载操作符:

const Money operator %(const Money& amount, double percentage) {
    int amountToCents = amount.getCents() + amount.getDollars() * 100;
    double pScaledMoney = amountToCents * percentage;
    int scaledDollars = abs((round(fabs(pScaledMoney / 100))) / 100);
    int scaledCents = abs((round(fabs(pScaledMoney / 100))) % 100);
    if (pScaledMoney < 0) {
        scaledDollars = -scaledDollars;
        scaledCents = -scaledCents;
    }
    return Money(scaledDollars, scaledCents);
}   

round()的返回值为浮点类型。数字运算符%不能与双精度或浮点数一起使用:

// error
(round(fabs(pScaledMoney / 100))) % 100
// fixed
((int)round(fabs(pScaledMoney / 100))) % 100

如果你担心损失的精度,最好使用版本的round函数返回整数,以避免问题,如c++:如何四舍五入的双精度为整型?和http://blog.frama-c.com/index.php?post/2013/05/02/nearbyintf1

C99和c++ 11有你需要的确切的功能:

long int lround (double x);

其他代码风格问题(与错误无关)

这两个函数不使用Money的任何私有成员,因此它们都不应该是友元或类成员。两者都可以在类外定义。

如果返回一个新对象,从函数返回const Money是没有意义的。