运算符重载可以通过两种方法来实现,用成员函数或者友元函数重载运算符。
在本文章中,有两个重要的内容:
第一个: 前置++ 和 后置++重载,后置++通过一个占位符来标明。
第二个: 单目运算符重载时,当作为成员函数时,操作数通过this指针隐式传递,不用在函数参数表明,而友元函数需要。双目运算符重载时,当作为成员函数时,左操作数通过this指针隐式传递,只需要声明一个参数就可以了,而友元函数需要声明两个参数。
代码如下:
#include<iostream>
using namespace std;
class Complex
{
private:
int a;
int b;
//全局函数 重载+运算符
friend Complex operator+(Complex& c1, Complex& c2);
//重载 前置++
friend Complex& operator++(Complex& c1);
friend Complex operator++(Complex& c1, int); //通过一个占位符int来说明是后置++
public:
Complex(int a = 0, int b = 0)
{
this->a = a;
this->b = b;
}
void printCom()
{
cout << a << " + " << b << "i" << endl;
}
public: