/*
* c++ 二元运算符重载, 以加法为例
*/
#include
class Complex
{
public:
int r=0; // real, 实部
int v=0; //virtual, 虚部
};
// 重载加法+ 操作符
// 可见,c++2元运算符,取其左侧为第一参数,右侧为第二参数
// 返回值可以付给新的变量
Complex operator+(Complex c1, Complex c2)
{
Complex c;
c.r = c1.r + c2.r;
c.v = c1.v + c2.v;
return c;
}
Complex hexout(Complex c)
{
printf("r:0x%x,v:0x%x\n",c.r,c.v);
return c;
}
int main()
{
Complex obj1,obj2,obj3;
obj1.r = 1;
obj1.v = 11;
obj2.r = 2;
obj2.v = 22;
obj3 = obj1 + obj2;
printf("obj3.r:%d, obj3.v:%d\n",obj3.r, obj3.v);
obj3 = obj1 + hexout(obj2);
return 0;
}
/* 执行结果
$ ./test_add
obj3.r:3, obj3.v:33
r:0x2,v:0x16
*/