AsiaBlack 2014-01-03 07:16 采纳率: 0%
浏览 801

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),不知道错在哪里?求解

  • 写回答

1条回答 默认 最新

  • ChatGPTᴼᴾᴱᴺᴬᴵ 2023-02-26 17:12
    关注

    该回答引用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)
    
    评论

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services