所以我一直遇到运营商重载问题。所以我有一个程序,它有一个名为Weight的对象,它有2个属性,磅和盎司。我想出了所有其他的操作员,但增量一直给我带来麻烦。我尝试这样做,但由于某种原因,它不想工作。
以下是头文件中的声明(包括2个变量):
void operator++();
void operator--();
private:
int pounds;
int ounces;
会员功能:
void Weight::operator++() {
pounds + 1;
ounces + 15;
}
void Weight::operator--() {
pounds - 1;
ounces - 15;
}
一切都有帮助!
发布的代码有两个问题。
Weight
对象时,不清楚这应该发生。它的价值应该上涨/下跌一盎司还是一磅。假设增量运算符将值更改为1盎司,则必须使用:
pounds + 1
此外,重载qazxsw poi运算符的规范实践是返回对象的引用。因此,你应该使用:
ounces + 15
你必须类似地更新void Weight::operator++() {
ounces++;
// If ounces becomes 16, we have to increment pounds by one and set ounces to zero.
if ( ounces == 16 )
{
pounds++;
ounces = 0;
}
// That can also be achieved by using.
// pounds += (ounces / 16);
// ounces = (ounces % 16);
}
功能。