运算符中的后缀++和前缀++重载C++,含义

Postfix ++ and prefix ++ in operatoroverloading C++, meanings

本文关键字:重载 C++ 含义 前缀 后缀 运算符      更新时间:2023-10-16

我有这段代码,但我不理解输出。。。

class Complex
{
   private:
       float re;
       float im;
   public:
       Complex(float r = 0.0, float i = 0.0) : re(r), im(i){};
       void Print(){cout << "Re=" << re <<",Im=" << im << endl;}
       Complex operator++(); //prefiksna
       Complex operator++(int); //postfiksna
};
 Complex Complex ::operator++()
{
    //First, re and im are incremented
    //then a local object is created.
     return Complex( ++re, ++im);
 }
Complex Complex ::operator++(int k)
{
   //First a local object is created
   //Then re and im are incremented. WHY is this ??????
    return Complex( re++, im++);
}
int main()
  {
   Complex c1(1.0,2.0), c2;
   cout << "c1="; c1.Print();
   c2 = c1++;
   cout << "c2="; c2.Print();
   cout << "c1="; c1.Print();
   c2 = ++c1;
   cout << "c2="; c2.Print();
   cout << "c1="; c1.Print();
   return 0;
}

输出为:

1.c1=Re=1,Im=2

2.c2=Re=1,Im=2

3。c1=Re=2,Im=3

4.c2=Re=3,Im=4

5.c1=Re=3,Im=4

有人能解释一下这些输出吗?(1.微不足道,我想我能理解。和5,只是想确保…)我对2的区别很感兴趣。和4。主要是,这还不清楚为什么会是这样。注释中的代码中也有一个问题(为什么是这样????)

你的问题应该像其他人一样结束,他们曾经问过"增量前和增量后意味着什么",但你的老师在尝试教授之前应该学习一些东西:

Complex& Complex ::operator++()
{
    //First, re and im are incremented
    ++re; ++im;
    //then there is no need to create a local object.
     return *this;
 }

通过测试它的方式,优化器可以消除讲师的错误代码所隐含的额外工作。但是,如果你应该学习如何编写前增量运算符和后增量运算符(这是学习它们的含义之外的一步),那么正确地学习如何以及为什么前增量运算符应该比后增量运算符更高效。