C++---运算符重载(2) 前置++重载 后置++重载

前置++重载

直接上代码

#include <iostream>
#include <string>
using namespace std;

class MyAdd{
   friend ostream & operator<<(ostream &cout, MyAdd a);
   public:
       MyAdd()
       {
         my_num = 0;
       }
       MyAdd & operator++() //返回一个对象
       {
         my_num++;
         return *this;
       }
   private:
       int my_num;
};

ostream & operator<<(ostream &cout, MyAdd a)
{
    cout << a.my_num << endl;
    return cout;
}

void example()
{
   MyAdd z;
   cout << ++z ;
   cout << ++z ;
}

int main()
{
     example();
     return 0;
}

用成员函数去重载前置++运算符,并切返回值类型为类对象本身,这跟上一篇文章提到的链式变成思想有关,方便后面继续对这个对象进行操作,而不给它造成障碍。

同样是++,怎么区分前置还是后置呢,我们在后置++的重载函数中使用一个占位参数,它并不被使用,只是做区分用
代码如下:

#include <iostream>
#include <string>
using namespace std;

class MyAdd{
   friend ostream & operator<<(ostream &cout, MyAdd a);//声明为友元,让它可以访问私有成员
   public:
       MyAdd()
       {
         my_num = 0;
       }
       MyAdd  operator++(int)
       {
         MyAdd tmp = *this;
         my_num++;
         return tmp;
       }
   private:
       int my_num;
};

ostream & operator<<(ostream &cout, MyAdd a)//重载输出运算符,方便直接输出类的对象属性
{
    cout << a.my_num << endl;
    return cout;
}

void example()
{
   MyAdd z;
   cout << z++ ;
   cout << z ;
}

int main()
{
     example();
     return 0;
}

这里的输出结果
在这里插入图片描述
与前置++重载函数不同的是,这里重载函数返回的是值
为什么不返回对象本身
1、
在这里插入图片描述
我们这里定义的是一个局部的对象,返回局部变量操作是非法操作
2、
如果++后直接返回,那就实现不了后置++的效果,也就是实现不了执行完语句之后,对象属性再递增的效果

总结

还有其他运算符可以重载,如赋值,函数调用运算符等
对运算符进行必要的重载,可以简化很多操作,但不宜滥用

发布了15 篇原创文章 · 获赞 33 · 访问量 9071

猜你喜欢

转载自blog.csdn.net/weixin_43086497/article/details/104974388