为什么要有运算符重载?
一些用于自定义类型,编译器不知道如何进行类型的运算。
运算符重载的本质是函数。
用两种方法实现运算符重载:
1、重载为成员函数,解释为:ObjectL.operator op(ObjectR),左边操作数ObjectL通过this指针传递,右操作数由参数Object传递
2、重载为友员函数,解释为:operator op(ObjectL,ObjectR),左右操作数都有参数传递
二元操作符,复数类举例子:
#include<iostream>
#include<cstdio>
using namespace std;
class Complex {
friend Complex operator+(Complex &c1, Complex &c2);//友元函数实现运算符重载
public:
Complex() {
this->a = 0;
this->b = 0;
}
Complex(int a, int b) {
this->a = a;
this->b = b;
}
Complex operator+(con