---- 整理自狄泰软件唐佐林老师课程
1. 需要解决的问题
- 下面的复数解决方案是否可行?
1.1 编程实验:复数的加法操作
#include <stdio.h>
class Complex
{
int a;
int b;
public:
Complex(int a = 0, int b = 0) {
this->a = a;
this->b = b;
}
int getA() {
return a;
}
int getB() {
return b;
}
friend Complex Add(const Complex& p1, const Complex& p2);
};
Complex Add(const Complex& p1, const Complex& p2)
{
Complex ret;
ret.a = p1.a + p2.a;
ret.b = p1.b + p2.b;
return ret;
}
int main()
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = Add(c1, c2); // c1 + c2
printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
return 0;
}
1.2 思考
Add 函数可以解决 Complex 对象相加的问题,但是 Complex 是现实世界中确实存在的复数,并且复数在数学中的地位和普通的实数相同。
- 为什么不能让 “ + ” 操作符也支持复数相加呢?
2. 操作符重载
- C++ 中的重载能够 扩展操作符的功能
- 操作符的重载 以 函数 的方式 进行
- 本质:用 特殊形式的函数 来扩展操作符的功能
- 通过 operator 关键字 可以定义特殊的函数
- operator 的 本质:通过 函数 来重载操作符
2.1 语法
- Sign 代表系统中预定义的操作符,如:+ 、- 、* 、/ 、… 等
2.2 编程实验:操作符重载初探
#include <stdio.h>
class Complex
{
int a;
int b;
public:
Complex(int a = 0, int b = 0) {
this->a = a;
this->b = b;
}
int getA() {
return a;
}
int getB() {
return b;
}
friend Complex operator + (const Complex& p1, const Complex& p2); // 注意这里的参数
};
Complex operator + (const Complex& p1, const Complex& p2)
{
Complex ret;
ret.a = p1.a + p2.a;
ret.b = p1.b + p2.b;
return ret;
}
int main()
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2;
printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
return 0;
}
- 可以将操作符重载函数定义为类的成员函数
- 比全局操作符重载函数 少一个参数(左操作数)
- 不需要依赖友元 就可以完成操作符重载
- 编译器 优先在成员函数中寻找操作符重载函数
2.3 编程实验:成员函数重载操作符
#include <stdio.h>
class Complex
{
int a;
int b;
public:
Complex(int a = 0, int b = 0) {
this->a = a;
this->b = b;
}
int getA() {
return a;
}
int getB() {
return b;
}
Complex operator + (const Complex& p) { // 留意一下参数
Complex ret;
printf("Complex operator + (const Complex& p)\n");
ret.a = this->a + p.a;
ret.b = this->b + p.b;
return ret;
}
friend Complex operator + (const Complex& p1, const Complex& p2);
};
Complex operator + (const Complex& p1, const Complex& p2)
{
Complex ret;
printf("Complex operator + (const Complex& p1, const Complex& p2)\n");
ret.a = p1.a + p2.a;
ret.b = p1.b + p2.b;
return ret;
}
int main()
{
Complex c1(1, 2);
Complex c2(3, 4);
Complex c3 = c1 + c2; // 等价于 c1.operator+(c2);
// 编译器优先在成员函数中寻找操作符重载函数
printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
return 0;
}
- 注解:实际上 Complex c3 = c1 + c2;等价于 Complex c3 = c1.operator+(c2);
3. 小结
- 操作符重载是 C++ 的强大特性之一
- 操作符重载的 本质 是通过 函数 扩展操作符的功能
- operator 关键字是实现操作符重载的关键
- 操作符重载 遵循 相同的函数重载规则
- 全局函数和成员函数都可以实现对操作符的重载