C++ 前缀++后 缀++重载的写法:
#include<iostream>
using namespace std;
class Complex
{
private:
int i_r;
int i_v;
public:
friend ostream& operator<<(ostream &cout,Complex &cp);
Complex(int i_r = 0,int i_v = 0)
{
this->i_r = i_r;
this->i_v = i_v;
}
~Complex()
{
}
Complex &operator++()//前缀++重载 返回的是引用
{
this->i_r++;
this->i_v++;
return *this;
}
Complex operator++(int)// 后缀++ 重载写法 (int) 区分前缀的必须写成int 返回是匿名对象
{
Complex temp=*this;
this->i_r++;
this->i_v++;
return temp;
}
};
ostream& operator<<(ostream &cout,Complex &cp)// 重载<<
{
cout<<cp.i_r<<"+"<<cp.i_v<<"i"<<endl;
return cout;
}
void main()
{
Complex cp(1,2);
cout<<cp<<endl;
cout<<++cp<<endl;
cout<<cp++<<endl;
system("pause");
}
由于operator++ 分前缀和后缀,C++编译器为了区分使用operator++(int)表示后缀 这里int 不具有传参功能,只是相当于一个标识。只能是int否则编译器会报错。