上一篇文章我们介绍了运算符重载的目的和一个简单的应用案例。但运算符重载绝非我们想想的那么简单和容易,有很多陷阱我们如果我们还没有去踩过,是不会了解清楚内部的工作原理的。本文只介绍一下运算符重载的两种方式,成员函数重载和友元函数重载,并不具体到某些运算符的具体案例。

成员函数重载(与上一篇文章一致):

#include

using namespace std;

class Complex
{
public:
Complex(int x, int y)
:_x(x), _y(y){}

// 重载+号运算符
Complex operator+(Complex& another)
{
// this此时是s1,another此时是s2
return Complex(
this->_x + another._x,
this->_y + another._y);
}
// 打印_x和_y的值
void display()
{
cout << “_x = “ << _x << endl;
cout << “_y = “ << _y << endl;
}

private:
int _x;
int _y;
};

int main(int argc, char* argv[])
{
Complex c1(10, 20);
Complex c2(15, 25);
// 构建一个新对象,其内容由c1 + c2得出
// 此时c1 + c2就会调用我们编写的operator+函数
// 此句等同于 c3 = c1.operator+(c2)
Complex c3 = c1 + c2;
c3.display();

return 0;
}

友元函数重载,与成员函数不同的是,全局的友元函数需要传递两个参数,因为他并没有在类中,所以成员函数的this必须转化一个为operator+的参数,否则无法完成函数功能:

#include

using namespace std;

class Complex
{
public:
Complex(int x, int y)
:_x(x), _y(y){}

// 将一个全局的 operator+ 函数声明为Complex的友元函数
friend Complex operator+(Complex& left, Complex& right);

// 打印_x和_y的值
void display()
{
cout << “_x = “ << _x << endl;
cout << “_y = “ << _y << endl;
}

private:
int _x;
int _y;
};

// 友元函数的实现,与类的成员函数不同的是,this变成了left参数
Complex operator+(Complex& left, Complex& right)
{
return Complex(left._x + right._x, left._y + right._y);
}

int main(int argc, char* argv[])
{
Complex c1(10, 20);
Complex c2(15, 25);
// 构建一个新对象,其内容由c1 + c2得出
// 此时c1 + c2就会调用我们编写的operator+函数
// 此句等同于 c3 = operator+(c1, c2)
Complex c3 = c1 + c2;
c3.display();

return 0;
}