分数类增量运算符重载解释

时间:2013-07-26 07:56:41

标签: c++ overloading operator-keyword increment fractions

自上个学期以来,我已经给了很多想法(老实说)。我仍然不完全确定这里发生了什么。有人能帮助和启发我吗?我对pre / postfix的区别很好。分数是如何递增的,这让我感到困惑

以前缀示例为例。 所以如果我有一个2/4的分数会增加到3/4?因为当我看到numer + = denom时,它会让我觉得它会返回2 + 2 + 4,即8。

// prefix increment operator
fraction& fraction::operator++() {
    numer += denom;
    return *this;
}

// postfix increment operator
fraction fraction::operator++(int) {        // Note dummy int argument
    fraction temp(*this);
    ++*this;                            // call the prefix operator
    return temp;

提前感谢大家:)

1 个答案:

答案 0 :(得分:3)

前缀功能将拼写为

numer = numer + denom;

因此,如果2/4numer = 2 + 4 = 6,则结果为6/4(因为denom保持不变)。由于n/n = 1适用于所有整数(0除外),(a+n)/n将始终增加1

后缀版本使用前缀版本进行上述计算。