写代码像菜虚鲲 2021-04-26 20:45 采纳率: 50%
浏览 30
已采纳

萌新小白提问,c++重载后置递增运算符

class MyData
{

public:

    int m_a;

    MyData()  
    {
        m_a = 0;
    }


    MyData& operator++(int)
    {
        MyData* temp = this;

        this->m_a++;

        return *temp;
    }

};


ostream& operator<<(ostream& cout, MyData d)
{
    cout << d.m_a;
    return cout;
}


int main()
{
    MyData d;
    cout << d++ << endl;
    cout << d << endl;

}

这里最后的两个输出都是1,想知道是哪里出了问题

  • 写回答

4条回答 默认 最新

  • 写代码像菜虚鲲 2021-04-26 20:58
    关注

    看明白了,this和temp都是地址,指向的同一个对象。*this改了*temp也会跟着改,我傻了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?