下面的复数解决方案是否可行?
复数的加法操作
#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;
}
我们将复数的加法实现为全局函数 Add,并将 Add 函数声明为 Complex 类的友元,这样 Add 函数可以访问到 Complex 类的私有成员
程序运行结果如下图所示:
思考
Add 函数可以解决 Complex 对象相加的问题,但是 Complex 是现实世界中确实存在的复数,并且复数在数学中的地位和普通的实数相同
为什么不能让 + 操作符也支持复数相加呢?
操作符重载
C++ 中的重载能够拓展操作符的功能
操作符的重载以函数的方式进行
本质:
- 用特殊形式的函数拓展操作符的功能
通过 operator 关键字可以定义特殊的函数
operator 的本质是通过函数重载操作符
语法:
操作符重载初探
#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; // operator + (c1, c2)
printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
return 0;
}
我们将 Add 函数替换为了 operator + 函数,这样是重载了加号运算符,并且这个加号重载函数为全局函数
第 42 行,两个 Complex 类相加,编译器会去寻找是否重载了加号运算符,然后会去寻找使用加号的两个类型是否和重载加号运算符的类型匹配,匹配的话则去调用这个加号重载函数
程序运行结果如下图所示:
可以将操作符重载函数定义为类的成员函数
比全局操作符重载函数少一个参数 (左操作数)
不需要依赖友元就可以完成操作符重载
编译器优先在成员函数中寻找操作符重载函数
成员函数重载操作符
#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 类的成员函数,这样就不需要声明友元了
成员函数的操作符重载会比全局函数的操作符重载少一个参数,因为成员函数有一个隐藏的 this 指针,可以拿到左操作数
如果同时定义了成员函数和全局函数的操作符重载,编译器会优先调用成员函数的操作符重载
程序运行结果如下图所示:
通过打印可以看出,第 52 行的加法调用的是成员函数的加号重载函数
小结
操作符重载是 C++ 的强大特性之一
操作符重载的本质是通过函数拓展操作符的功能
operator 关键字是实现操作符重载的关键
操作符重载遵循相同的函数重载规则
全局函数和成员函数都可以实现对操作符的重载