实现算数操作符 + 、 - 、自增运算符++等一般有两种方法:
第一种方法:类操作符
此时,操作符函数是类的成员函数。
第二种方法:全局操作符
此时,重载的是全局操作符,需要把一个操作符函数(类似于全局函数)声明为类的友元。
#include<iostream>
using namespace std;
class Complex {
public:
Complex() {//构造函数初始化复数为0+0i
this->imag = 0;
this->real = 0;
};
Complex operator + (const Complex& other);//声明复数加复数
Complex operator + (int n);;//声明复数加整数
friend Complex operator + (int a, const Complex& b);//声明整数加复数
friend Complex operator - (const Complex& a, const Complex& b);//声明复数减复数
friend Complex operator - (int a, const Complex& b);//声明整数减复数
friend Complex operator - (const Complex& a, int b);//声明复数减整数
Complex& operator ++ () {//前置++
this->real++;
this->imag++;
return *this;
}
Complex& operator ++ (int) {//后置++
Complex a = *this;
a.real++;
a.imag++;
return a;
}
friend ostream& operator << (ostream&, Complex&);//声明重载运算符“<<”
friend istream& operator >> (istream&, Complex&);//声明重载运算符“>>”
private:
int real;//复数的实部
int imag;//复数的虚部
};
Complex Complex::operator + (const Complex& other) {//复数加复数的实现
this->real = this->real + other.real;
this->imag = this->imag + other.imag;
return *this;
};
Complex Complex::operator + (int n) {//复数加整数的实现
this->real = this->real + n;
return *this;
}
Complex operator + (int a, const Complex& b)//整数加复数的实现
{
Complex result;
result.real = a + b.real;
return result;