视频教程(北大mooc):
https://www.icourse163.org/learn/PKU-1002029030?tid=1002785058#/learn/content?type=detail&id=1003870385&cid=1004682687&replay=true
菜鸟教程:
http://www.runoob.com/cplusplus/cpp-overloading.html
/*
运算符重载形式
返回值类型 operator 运算符(形参表)
{
}
*/
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
class Complex
{
public:
double real,image;
public:
Complex(double real=0,double image=0);
void Print();
Complex operator+(const Complex &complex1)//重载为成员函数时,参数个数为运算符目数减一
{
Complex complex;
complex.real=this->real+complex1.real;
complex.image=this->image+complex1.image;
return complex;//返回一个临时对象
}
};
Complex operator -(const Complex &complex1,const Complex &complex2)//重载为普通函数时,参数个数为运算符目数
{
Complex complex;
complex.real=fabs(complex1.real-complex2.real);//real和image须为公有成员;
complex.image=fabs(complex1.image-complex2.image);
return complex;//返回一个临时对象
}
Complex::Complex(double real,double image)
{
this->real=real;
this->image=image;
}
void Complex::Print()
{
printf("real=%.2f,image=%.2f\n",this->real,this->image);
}
int main()
{
Complex complex1(1,2);
Complex complex2(3,4);
Complex complex3(0,0);
complex3=complex1+complex2;//等价于complex3=complex1.operator+(complex2);因为operator+定义成了成员函数;
complex3.Print();
complex3=complex1-complex2;//等价于complex3=operator-(complex1,complex2);因为operator-定义成了普通函数;
complex3.Print();
return 0;
}