首页 > 其他 > 详细

一元运算符重载

时间:2020-05-02 23:47:09      阅读:62      评论:0      收藏:0      [点我收藏+]

 

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

为将前置与后置的函数区分开,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执行--

        t1->a--;

       t1->b--;

       return  t;

    }

 

int main()

{      temp t1(0,0);

        ++t1;

        t1--;

        t1++;

}

 

一元运算符重载

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!