重载Postfix和前缀运算符

cod*_*dex -3 c++ class operator-overloading

我想知道这是否是重载post和pre increment运算符的正确代码.

如何在main()中调用这些运算符.

class fix{
int x;
int y;
public:fix(int = 0, int = 0);
   fix operator++(){//prefix increment
       fix a;
       ++a.x;
       ++a.y; 
       return a;
}
   fix operator++(int){ //post fix increment
       fix c;
       c.x = x;
       c.y = y;
       x++; y++;
       return c;
   }
};
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 5

这个运营商

   fix operator++(){
       fix a;
       ++a.x;
       ++a.y; 
       return a;
}
Run Code Online (Sandbox Code Playgroud)

不适用于原始对象.也就是说它不会改变原始对象.当然,你可以用这种方式定义它,但它会使用户感到困惑并且有不寻常的行为.

最好按以下方式定义它

   fix & operator ++()
   {
       ++x;
       ++y; 
       return *this;
   }
Run Code Online (Sandbox Code Playgroud)

至于后缀运算符,则正确定义.至于我,我会用以下方式定义它

   const fix operator ++( int )
   {
       fix c( *this );
       ++x; ++y;

       return c;
   }
Run Code Online (Sandbox Code Playgroud)

或者您可以通过以下方式定义它

   const fix operator ++( int )
   {
       fix c( *this );

       ++*this; // or operator ++()

       return c;
   }
Run Code Online (Sandbox Code Playgroud)

在主要中,它们可以被称为例如以下方式

fix f1( 10, 10 );
fix f2 = f1++;
fix f3( 10, 10 );
fix f4 = ++f1;
fix f5( 10, 10 );
fix f6 = f5.operator++( 0 );
fix f7( 10, 10 );
fix f8 = f7.operator++();
Run Code Online (Sandbox Code Playgroud)