初步C++运算符重载学习笔记<3> 增量递减运算符重载

初步C++运算符重载学习笔记<1>
初探C++运算符重载学习笔记<2> 重载为友元函数
 
 

增量、减量运算符++(--)分别有两种形式:前自增++i(自减--i)。后自增i++(自减i--)

因此当我们重载该运算符时,要重载对应形式的运算符。

T & operator ++() // 前自增++i

T & operator ++(int) //后自增 i++

 

 

举例:

#include <iostream>
using namespace std;

class complex
{
    double re;
    double im;
public:
    complex(double _re,double _im):re(_re),im(_im){};
    void print(){cout<<re<<" "<<im<<endl;}
    friend complex operator+(const complex &a ,const complex &b);  //想想返回为什么不是complex &
    complex& operator++();
    complex& operator++(int);
};

complex operator+(const complex &a , const complex &b)
{
    return complex(a.re + b.re , a.im + b.im );
}

complex& complex::operator++()   //前自增 ++i
{
    re = re + 1;
    return *this;
}

complex& complex::operator++(int)  //后自增 i++ int仅仅是区分前后自增
{
    im = im + 1;
    return *this;
}

int main()
{
    complex a(1,2);
    complex b(3,4);
    complex c = a + b;
    complex d = a + b + c;
    c.print();
    d.print();

    (c++)++;
    c.print();
    ++(++d);
    d.print();
    return 0;
}


结果输出为:

 

c后自增两次 虚部由6到8

d前自增两次 实部从10到12

 

 

 

 

 

 

版权声明:本文博客原创文章,博客,未经同意,不得转载。

posted @ 2015-07-06 21:11  lcchuguo  阅读(198)  评论(0编辑  收藏  举报