运算符重载的本质是 函数的调用
重载运算符函数可以对运算符做出新的解释,但原有基本语意不变
1、不改变运算符的优先级
2、不改变运算符的结合性
3、不改变运算符所需要的操作数
4、不能创建新的运算符
运算符重载的两种方法
用成员或友元函数重载运算符
1、运算符可以重在为成员函数或友元函数
2、关键区别在于成员函数具有this指针,友元函数没有this指针
3、不管是成员函数还是友元函数重载,运算符的使用方法相同,但传递参数的方式不同,实现代码不同,应用场合也不同
#include<iostream>
using namespace std;
//运算符重载的本质 是函数调用
class Complex
{
public:
Complex(int a=0, int b=0)
{
this->m_a = a;
this->m_b = b;
}
public:
int m_a;
int m_b;
};
Complex Add(Complex &t1, Complex &t2)
{
Complex tmp(t1.m_a + t2.m_a, t1.m_b + t2.m_b);
return tmp;
}
Complex operator+(Complex &t1, Complex &t2)
{
Complex tmp(t1.m_a + t2.m_a, t1.m_b + t2.m_b);
return tmp;
}
void main()
{
Complex c1(1, 2);
Complex c2(3, 4);
//Complex c3 = operator +(c1, c2);//第一种写法
Complex c4 = c1 + c2;//第二种写法
cout <<c4.m_a <<"+"<<c4.m_b<<"i"<< endl;
system("pause");
}