运算符重载(Operator Overload)
前面用到的运算符<<,本身在 C 语言中,是位操作中的左移运算符。现在又用作流插入运算符,这种一个运算符多种用处的现像叫作运算符重载。
在 C 语言中本身就有重载的现像,比如 & 既表示取地址,又表示位操作中的与运算。 *既表示解引用,又表示乘法运算符。只不过此类功能,C 语言并没有对开发者开放这类功能。
C++提供了运算符重载机制。可以为自定义数据类型重载运算符。实现构造数据类型也可以像基本数据类型一样的运算特性。
比较两个结构体是否相等
我们直接来比较结构体是否相等:之前是不可以的,但是使用运算符重载就可以解决。
例如下面代码:
#include <iostream>
using namespace std;
typedef struct _pos
{
int x_;
int y_;
}Pos;
int main()
{
Pos ps = {1,2 };
Pos fdPs = { 3,4 };
ps == fdPs;
return 0;
}
编译时直接会报错的,以前我们通过结构体成员进行比较相等。
我们给出以下代码:
#include <iostream>
using namespace std;
typedef struct _pos
{
int x_;
int y_;
}Pos;
bool operator == (Pos one, Pos another)
{
if (one.x_ == another.x_ && one.y_ == another.y_)
return true;
else
return false;
}
int main()
{
Pos ps = {1,2 };
Pos fdPs = { 3,4 };
if (ps == fdPs)
cout << "==" << endl;
else
cout << "!=" << endl;
return 0;
}
执行结果为:
如果我们把主函数里面的内容修改为:
int main()
{
Pos ps = {1,2 };
Pos fdPs = { 1,2 };
if (ps == fdPs)
cout << "==" << endl;
else
cout << "!=" << endl;
return 0;
}
执行结果为:
我们对于主函数里面进行修改:
int main()
{
Pos ps = {1,2 };
Pos fdPs = { 1,2 };
if (operator==(ps,fdPs))
cout << "==" << endl;
else
cout << "!=" << endl;
return 0;
}
执行结果为:
有的读者可能会提出,这里的也是进行成员比较的,但是这里的和之后的是由很大的区别的,以前的每次比较相等的时候都要写,现在既可以直接使用。运算符是==全局的,在任何位置到可以使用,我们在全局范围内重载 ,引入关键字operator把全局范围内的==重载,重载之后就会根据类型去找,找到了通过返回bool类型做判断。以前我们实现计算只能在自定义类型,现在构造类型也可以进行运算。
虚数求加法运算
#include <iostream>
using namespace std;
struct Complex
{
float real;
float image;
};
Complex operator+(Complex one, Complex another)
{
Complex sum;
sum.real = one.real + another.real;
sum.image = one.image + another.image;
return sum;
}
int main()
{
Complex com1 = { 1,2 };
Complex com2 = { 3,4 };
Complex sum = com1 + com2;
cout << "(" << sum.real << "," << sum.image << ")" << endl;
return 0;
}
执行结果为:
主函数进行修改:
int main()
{
Complex com1 = { 2,2 };
Complex com2 = { 4,4 };
Complex sum = operator+(com1, com2);
cout << "(" << sum.real << "," << sum.image << ")" << endl;
return 0;
}
执行结果为:
小结
我们给出的例子中重载了一个全局的操作符+号用于实现将两个自定义结构体类型相加。本质是函数的调用。本博客,只是一个运算符重载的引例,后序博客,我们会更加深入的说明运算符重载。函数运算符的重载远不止这些内容。