这在c ++中.它是如何工作的?

Jac*_*ack 0 c++ this

我对我的C++作业有疑问.我只是对此感到困惑.

下面的代码是我的.

我的问题是为什么=运算符中的if语句中的条件为真?

#include <cstring>
class abc {
      char p[9];
      int inc;
   public:
      abc( ) { inc = 8; strcpy(p, "10010101"); }
      ~abc( );
      abc& operator=(const abc &);

};

abc::~abc( ) {

}
abc& abc::operator=(const abc &c) {
   if(this != &c) { //my question is why this condition is true?
      inc = c.inc - 2;
      for(int i=0; i<inc; i++) {
     p[i] = c.p[i] + 2;
      }
   }
   return *this;
}

int main( ) {
   abc x, y;
   x = y;
   return 0;

}
Run Code Online (Sandbox Code Playgroud)

EdC*_*ica 5

因为如果你要分配给自己,你不想制作副本,这就是if条件的原因,*this返回自我实例.因为你试图分配的确y to x和他们都不同的情况下,你再做出copyy to x.