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.