一元运算符重载

一元运算符常用的有:  前置++、后置++、前置--、后置--;

为将前置与后置的函数区分开,C++规定:

前置: operator++(temp& t1);

后置:operator++(temp& t1,int i);//int i是编译器为了与前置++函数区分开,添加的一个无用的形参

同理:前置--,后置--

class  temp

{

    public:

           temp(int a, int b)

        {       

               this->m_a=a;

               this->m_b=b;

        }

//用全局函数实现后置--

      friend temp& operator--(temp& t,int i);

//用内部函数实现后置++

 temp& operator++(int i)

{

         temp t3=*this;

        this->a++;

        this->b++;

       return t3;

}

//用内部函数实现前置++

      temp& operator++()

     {

            this->a++;

           this->b++;

           return *this;

     }

private:

         int m_a;

         int m_b;

}

  

//定义重载函数--

temp&  operator--(temp& t1,int i)

   {

        temp t=t1;  //初始化一个对象后啊,在对t1执行--

        t.m_a--;

       t.m_b--;

       return  t;

    }

int main()

{      temp t1(0,0);

        ++t1;

        t1--;

        t1++;

}

原文地址:https://www.cnblogs.com/lyjbk/p/12820058.html