可重载的运算符列表:
双目算术运算符 + (加),-(减),*(乘),/(除),% (取模)
关系运算符 ==(等于),!= (不等于),< (小于),> (大于>,<=(小于等于),>=(大于等于)
逻辑运算符 ||(逻辑或),&&(逻辑与),!(逻辑非)
单目运算符 + (正),-(负),*(指针),&(取地址)
自增自减运算符 ++(自增),--(自减)
位运算符 | (按位或),& (按位与),~(按位取反),^(按位异或),,<< (左移),>>(右移)
赋值运算符 =, +=, -=, *=, /= , % = , &=, |=, ^=, <<=, >>=
空间申请与释放 new, delete, new[ ] , delete[]
其他运算符 ()(函数调用),->(成员访问),,(逗号),[](下标)
不可重载的运算符列表:
.:成员访问运算符
.*, ->*:成员指针访问运算符
:::域运算符
sizeof:长度运算符
?::条件运算符
#: 预处理符号
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(){
lValue = 0;
rValue = 0;
}
Complex(int a,int b):lValue(a),rValue(b){}
/*Complex operator +(Complex a){return Complex(this->lValue + a.lValue,this->rValue + a.rValue);}
Complex operator -(Complex a){return Complex(this->lValue - a.lValue,this->rValue - a.rValue);}
Complex operator *(Complex a){return Complex(this->lValue * a.lValue,this->rValue * a.rValue);}
Complex operator /(Complex a){return Complex(this->lValue / a.lValue,this->rValue / a.rValue);} */
Complex operator ++(int n){Complex p =*this;this->lValue++;this->rValue ++;return p;} //i++
Complex operator ++(){this->lValue++;this->rValue ++;return *this;} //++i
friend Complex operator +(Complex &b,Complex &a){return Complex(b.lValue + a.lValue,b.rValue + a.rValue);}
friend Complex operator -(Complex &b,Complex &a){return Complex(b.lValue - a.lValue,b.rValue - a.rValue);}
friend Complex operator *(Complex &b,Complex &a){return Complex(b.lValue * a.lValue,b.rValue * a.rValue);}
friend Complex operator /(Complex &b,Complex &a){return Complex(b.lValue / a.lValue,b.rValue / a.rValue);}
friend ostream & operator <<(ostream &output,const Complex &a)
{
output<<a.lValue<<" : "<<a.rValue<<endl;
return output;
}
/*ostream & operator<<(ostream &output)
{
output<<this->lValue<<" : "<<this->rValue<<endl;
return output;
}*/
double operator () (int a, int b)
{
return a*b*lValue*rValue;
}
private:
int lValue;
int rValue;
};
int main()
{
Complex a1(1,2);
Complex a2(2,3);
//a1<<cout; //member reload call
cout<<a1;
cout<<a2;
cout<<a1+a2;
cout<<a1-a2;
cout<<a1*a2;
cout<<a1/a2;
cout<<a1++;
cout<<++a2;
cout<<a1(1,5);
return 0;
}
output:
$ ./a.exe
1 : 2
2 : 3
3 : 5
-1 : -1
2 : 6
0 : 0
1 : 2
3 : 4
30