在预增量操作期间对象会发生什么?

时间:2017-12-12 18:04:03

标签: c++

我有这门课,但我无法理解创建++ c时会发生什么。什么回报*这意味着什么?抱歉我的英文。

class Cls{

int i;
public:
  Cls(int i=8):i(i){cout<<'A';}
  Cls(const Cls &t):i(t.i){cout<<'B';}
  ~Cls(){cout<<'C';}
  void af(){cout<<i;}
  Cls operator+(Cls &t){return Cls(i+t.i);}
  Cls operator++(){i++; return *this;}
  Cls& operator--(){--i; return *this;}
  operator int(){cout<<'D'; return i;}

  };

  int main(){

      Cls c; cout <<","; //Here the constructor will print A
      ++c; cout <<",";   // here?
      c.af(); cout <<","; //This will print 9

           //Then the destructor will print C.
      return 0;
  }

实际输出是:

A,BC,9,C

我希望它应该打印出来:

A,,9,C

为什么要打印BC

1 个答案:

答案 0 :(得分:1)

预增量运算符方法返回 new 对象。它会调用构造函数,稍后会调用析构函数。

Cls operator++(){i++; return *this;}
^^^  return by value.
     Means you need to be able to copy construct "Cls"

请注意,您通常会将其写为:

Cls& operator++(){i++; return *this;}
  ^^^   To return the object by reference (and thus avoid construction/destruction).

您还应该注意,如果您提高了所使用的优化级别,那么“BC”可能会消失,因为编译器可以轻松地“删除”复制操作作为优化。