This question already has answers here:
What are the basic rules and idioms for operator overloading?
                                
                                    (7个答案)
                                
                        
                                3个月前关闭。
            
                    
根据我的理解,重载后缀运算符对变量的影响将反映在变量的下一次出现中。

但是下面的程序与我的理解相矛盾,

请帮助我了解以下程序中发生的情况。

#include <iostream>

typedef struct Rectangle_Tag
{
    int len;
    int breadth;

}Rectangle_S;

/* Overloading an infix opertor */
Rectangle_S operator+(Rectangle_S a, Rectangle_S b)
{
    Rectangle_S c;

    c.len = a.len + b.len;
    c.breadth = a.breadth + b.breadth;

    return c;
}

/* Overloading a prefix opertor */
Rectangle_S operator++(Rectangle_S &a)
{
    a.len += 1;
    a.breadth += 1;

    return a;
}

/* Overloading a postfix opertor */
Rectangle_S operator++(Rectangle_S &a, int val)
{
    a.len += 1;
    a.breadth += 1;

    return a;
}

int main(void)
{
    Rectangle_S r1, r2, r3;

    r1.len = 20;
    r1.breadth = 10;

    r2.len = 20;
    r2.breadth = 10;

    r3 = (r1++) + (r2);

    std::cout << "\tr3.len     : " << r3.len << '\n';
    std::cout << "\tr3.breadth : " << r3.breadth << '\n';

    return (0);
}


//Expected Output :
    r3.len     : 40
    r3.breadth : 20

//Actual Output :
    r3.len     : 41
    r3.breadth : 21

最佳答案

没有人是完美的!

该代码的作者以一种特殊的方式实现了后缀运算符。正确的方法是

Rectangle_S operator++(Rectangle_S &a, int)
{
    auto old = a;
    ++a;
    return old;
}


还要注意,前缀++应该通过引用返回修改后的对象。

10-06 00:58