c++重载问题:我在运行后发现重载的后置--操作符没起到应有的作用,求解。

#include
using namespace std;

class complex
{
double real,imag;
public:
complex(double r=0,double i=0)
{
real=r;
imag=i;
}

const complex operator--(int)
{

    complex temp(*this);
    --(*this);
    return temp;
}
const complex operator--()
{

       --real;--imag;
       return *this;
}


void display();

};

void complex::display()
{
if(imag>=0)
{
cout<<"("<<real<<"+"<<imag<<"i)"<<endl;
}
else
cout<<"("<<real<<imag<<"i)"<<endl;
}

int main()
{
complex c1(1,1);
cout<<"c1=";c1.display();

--c1;
cout<<"--c1,c1=";c1.display();
c1--;
cout<<"c1--,c1=";c1.display();

return 0;

}
运行结果:
c1=(1+1i)
--c1,c1=(0+0i)
c1--,c1=(-1-1i)

我预想的结果应该是c1--,c1=(0+0i),不知道错在哪里?求解

该回答引用ChatGPT

根据你提供的代码,你的重载后置--运算符返回了一个常量complex对象。这个常量对象是临时对象,是一个副本,它的值是被递减前的原始值。这意味着,当你执行c1--操作时,实际上是将c1对象的值减1,并返回一个临时副本,这个副本的值是减1前的值。因此,当你在执行c1--之后打印c1对象时,你得到的是减1后的值。


为了得到你预期的结果,你可以将后置--运算符的返回类型更改为非常量类型,并返回对象的引用。这样,当你执行c1--操作时,你得到的是减1后的对象,并且可以将其打印出来。


修改后的代码如下:

class complex {
    double real, imag;
public:
    complex(double r = 0, double i = 0) {
        real = r;
        imag = i;
    }

    complex& operator--() {
        --real;
        --imag;
        return *this;
    }

    complex operator--(int) {
        complex temp(*this);
        --(*this);
        return temp;
    }

    void display();
};

void complex::display() {
    if (imag >= 0) {
        cout << "(" << real << "+" << imag << "i)" << endl;
    }
    else {
        cout << "(" << real << imag << "i)" << endl;
    }
}

int main() {
    complex c1(1, 1);
    cout << "c1=";
    c1.display();

    --c1;
    cout << "--c1, c1=";
    c1.display();

    c1--;
    cout << "c1--, c1=";
    c1.display();

    return 0;
}

输出结果:

c1=(1+1i)
--c1, c1=(0+0i)
c1--, c1=(0+0i)