uacs2024

导航

复试C++19真题_看程序写结果_前置++运算符重载 易错

考察前置++运算符设置为友元函数,这题的坑在于,返回值是不是对象的引用,形参也不是对象的引用,导致自增离开了作用域以后就不在有任何效果。

#include <iostream>
using namespace std;

class C{
private:
    int xx,yy;
public:
    C(int x,int y):xx(x),yy(y)  {}
    friend C operator++(C);
    void print()  {cout << xx << "," << yy << endl;}
};

C operator++(C c){
    ++c.xx;
    ++c.yy;
    return c;
}

int main(){
    C aa(10,20);
    aa.print();
    for(int i=0;i<5;i++)  ++aa;
    aa.print();
}

结果

10,20
10,20

 简单修改了一下

#include <iostream>
using namespace std;

class C{
private:
    int xx,yy;
public:
    C(int x,int y):xx(x),yy(y)  {}
    friend C &operator++(C &c); //注意区别
    void print()  {cout << xx << "," << yy << endl;}
};

C &operator++(C &c){  //注意区别
    ++c.xx;
    ++c.yy;
    return c;
}

int main(){
    C aa(10,20);
    aa.print();
    for(int i=0;i<5;i++)  ++aa;
    aa.print();
}

结果

10,20
15,25

 

posted on 2024-03-22 15:00  ᶜʸᵃⁿ  阅读(4)  评论(0编辑  收藏  举报