C++运算符重载(一元、二元运算符)
对自定义类对象Complex进行+运算符的重载
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(int a=0,int b=0)
{
this->a = a;
this->b = b;
}
//前置-- --c
Complex& operator--()
{
this->a--;
this->b--;
return *this;
}
//后置-- 使用int占位符,与前置--区分开
Complex& operator--(int)
{
Complex temp = *this;
this->a--;
this->b--;
return temp;
}
public:
int a;
int b;
};
Complex operator+(Complex &c1, Complex &c2)
{
Complex temp(c1.a + c2.a,c1.b + c2.b);
return temp;
}
//后置++ 使用int占位符,与前置++区分开
Complex operator++(Complex &c1,int)
{
//先使用c1,再进行加操作
Complex temp = c1;
c1.a++;
c1.b++;
return temp;
}
//前置++ ++c 使用相加后的c
Complex& operator++(Complex &c1)
{
c1.a++;
c1.b++;
return c1;
}
int main()
{
Complex c1(1,2), c2(3,4);
Complex c3;
c3 = c1 + c2;
cout << c3.a << " " << c3.b << endl;
--c3;
cout << c3.a << " " << c3.b << endl;
++c3;
cout << c3.a << " " << c3.b << endl;
c3++;
cout << c3.a << " " << c3.b << endl;
c3--;
cout << c3.a << " " << c3.b << endl;
system("pause");
return 0;
}
运算符重载的本质是函数调用,他的本质就是一个函数。
重载运算符函数可以对运算符做出新的解释,但原有的基本语义不变:
(1)不改变运算符的优先级
(2)不改变运算符的结合性
(3)不改变运算符所需要的操作数
(4)不能创建新的运算符
运算符函数可以重载为成员函数或友元函数,关键区别在于成员函数具有this 指针,友元函数没有this指针,不管是成员函数还是友元函数重载,运算符的使用方法相同。但传递参数的方式不同,实现代码不同,应用场合也不同