用成员函数和友元函数重置单目运算符(++后缀和前缀)

运算符重载疑难知识点:点击打开链接

单目运算符“++”和“--”的重载

 在C++,可以通过在运算符函数参数表中是否插入关键字int来区分前缀和后缀这两种方式。

    ◆对于前缀方式++ob,可以用运算符函数重载为

         ob.operator ++();             // 成员函数重载

   或 operator ++ (X& ob);      // 友元函数重载,

                                             其中ob为类X对象的引用

    ◆ 对于后缀方式ob++,可以用运算符函数重载为

        ob.ooperator ++(int);         // 成员函数重载

   或 operator++(X& ob,int);     // 友元函数重载

在调用后缀方式的函数时,参数int一般被传递给值0

以下为具体例子:

a.何用成员函数重置单目运算符

class Time

{public:

       Time(){minute=0;sec=0;}

       Time(intm,int s):minute(m),sec(s){ }

       Time operator++( );    //声明前置自增运算符“++”重载函数

       Time operator++(int);   //声明后置自增运算符“++”重载函数

         void display(){cout<<minute<<“minute”<<sec<<“sec”<<endl;}

private:

       intminute;

       intsec;

};

Time Time∷operator++( )    //定义前置自增运算符“++”重载函数

{       sec++;

       if(sec>=60)

       {     

              sec=0;         //满60秒进1分钟

              ++minute;

       }

       return *this;         //返回当前对象值

}

Time Time∷operator++(int)  //定义后置自增运算符“++”重载函数

{

       Time temp(*this);

       sec++;

       if(sec>=60)

       {

              sec=0;

              ++minute;

       }

       return temp;         //返回的是自加前的对象

}

b)     如何用成员函数重置单目运算符

friend void operator ++(Point &point)//重载前缀++

{++point.x;   ++point.y;}

 

friend Point operator ++(Point&point,int a) //重载后缀++

{     

Point p(1,1); //创建任意一个对象

    p=point;

       ++point.x;   

       ++point.y;

       returnp;

}

猜你喜欢

转载自blog.csdn.net/sdz20172133/article/details/80905353
今日推荐