为什么需要 运算符重载?
当我们简单将两个整数相加时,c++编译器知道究竟该怎么做,但是当我们将两个复数类进行相加时,c++编译器并不知道该怎么做,此时就需要操作符重载。
操作符重载函数形式一般分为两种:
1. 全局函数(友元函数)
2. 成员函数
下面代码计算了两个复数对象之间相加与相减。 其中 + 运算符重载通过 友元函数 实现, - 运算符重载通过 成员函数 实现。
#include <iostream>
using namespace std;
class Complex {
private:
int a;
int b;
friend Complex operator+(Complex& c1, Complex& c2); //友元函数声明
public:
Complex(int a=0, int b=0) {
this->a = a;
this->b = b;
}
//打印复数形式输出
void Print() {
cout << this->a << " + " << this->b << "i" << endl;
}
//成员函数 形式 重载 -
Complex &operator-(Complex& c1) {
this->a = this->a - c1.a;
this->b = this->b - c1.b;
return *this;
}
};
Complex operator+(Complex& c1, Complex& c2) {
Complex tmp;
tmp.a = c1.a + c2.a;
tmp.b = c1.b + c2.b;
return tmp;
}
int main()
{
Complex c1(1, 2), c2(3, 4);
Complex c3;
// 全局函数形式 重载 + 运算符
c3 = c1 + c2;
c3.Print();
//成员函数形式 重载 - 运算符
//Complex c4;
c2 = c2 - c1;
c2.Print();
cout << "Hello World!\n";
system("pause");
}