18、C++运算符重载之++ -- [ ]

C++运算符重载之++ --  [ ]

++ -- 可以使用成员函数,也可以使用友元函数来进行重载,而且还有前后缀之分。

[ ]     只能使用成员函数来进行重载,而且C++规定只能有一个参数,而且必须有一个。

测试实例:

#include <iostream>

using namespace std;

class CComplex{

    private:

        double real;

        double imag;

    public:

    CComplex(double r,double i):real(r),imag(i)

    {

    }

    CComplex(const CComplex &com)//复制构造函数

    {

        real=com.real;

        imag=com.imag;

        cout<<"调用复制构造函数"<<endl;

    }

    CComplex & operator =(const CComplex &com)

    {

        real=com.real;

        imag=com.imag;

        cout<<"调用赋值=操作符"<<endl;

        return *this;

    }

    ~CComplex()

    {

    }

    void print()

    {

        cout<<"real="<<real<<",imag="<<imag<<endl;

    }

    //成员函数 重载 运算符 ++ 前缀和后缀  以及操作符[]

    CComplex operator ++()//前缀

    {

        ++real;

        ++imag;

        return *this;

    }

    CComplex operator ++(int )//后缀 默认为0 隐式调用时,会自动赋值0 显示调用需要指定值为0

    {

        CComplex temp(*this);//构造一个临时对象

        real++;

        imag++;

        return temp;//返回改变前的

    }

    double operator [](int i) //C++规定只能有一个参数,而且必须有一个参数

    {

        return  real+i;

        //如果return 的类型是一个类内成员的引用,就可以对这个成员进行读写操作了。

    }

    //友元函数 重载 运算符 --

    friend CComplex operator --(CComplex &com)

    {

        --(com.real);

        --(com.imag);

        return com; //返回改变以后的

    }

    friend CComplex operator --(CComplex &com,int)

    {

        CComplex temp(com);

        com.real--;

        com.imag--;

        return temp;//返回改变以前的。

    }

};

int main()

{

    //返回类型为值类型时,会调用复制构造函数

    CComplex com1(1,2);

    (com1++).print();//先执行com1.print() 再调用 com1++;返回一个对象类型

    (++com1).print();//先执行++com1 ,返回一个对象类型,再调用这个com1.print();

    CComplex com2(4,4);

    (com2--).print();

    (--com2).print();

    cout<<com2[10]<<endl;

    return 0;

}


程序运行结果:

调用复制构造函数

real=1,imag=2

调用复制构造函数

real=3,imag=4

调用复制构造函数

real=4,imag=4

调用复制构造函数

real=2,imag=2

12

Process returned 0 (0x0)   execution time : 1.570 s

Press any key to continue.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值