重载操作符类型错误
Overloaded Operator Type Error
我创建了一个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
是没有意义的。
相关文章:
- 我的模板类方法返回错误类型?
- 错误:类型"double()"和"double()"的操作数无效到二进制&quo
- 类型为 "int*" 的参数与 C++ 中错误类型"int**"参数不兼容
- glDrawElements GL 错误类型 = 0x824c,严重性 = 0x9146,消息 = GL_INVALID
- Eclipse/CDT_C++给出"语义错误_"类型XXX无法解决"。项目运行
- turbo 为什么我的C++代码中出现错误类型名称预期"错误?
- "auto"推断出 hashtable_policy.h 中的错误类型
- 设计自己的结果/两者之一:是否应该始终指定成功类型和错误类型
- 如何修复"ctypes"。参数错误:参数 2:<键入"异常.类型错误">:RaspberryPi 中的错误类型"错误
- 在 vscode 上编译错误.类型说明符是 C++11 扩展
- 不允许使用错误类型
- 当读取错误类型时,CIN覆盖我的初始化值
- C++:"错误:类型'const char*'和'const char [28]'的操作数无效到二进制'ope
- 我的代码错误类型警告 1 警告 C4018 和更多错误
- 在shared_from_this()中的错误类型(在继承类中)(是否有dyn.type-ware shared Poi
- 为什么缩小转换范围不能防止错误类型的map.insert()失败
- 程序总是返回二进制'>>':找不到运算符,它采用错误类型的左操作数
- 错误:类型为 '.&' 来自类型的临时 '..*康斯特'
- 涉及将要馈送的向量转换为execvp的错误类型
- C++中是否存在错误类型