C++ 中的运算符重载
你可以重新定义或重载的大部分 C++ 已有的操作符。因此,程序员可以像使用用户自定义类型一样使用操作符。
重载操作符是一类函数,它们就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。像任何其它函数,重载运算符也有返回类型和参数列表。
Box operator+(const Box&);
声明加法运算符可以用来使两个 Box 对象相加并返回最终 Box 对象。大多数重载运算符可以被定义为普通非成员函数或类成员函数。如果我们把上面的函数定义为一个类的非成员函数,那么我们就必须为每个操作数传两个参数如下:
Box operator+(const Box&, const Box&);
下面是通过使用成员函数来展示运算符重载的概念的示例。这里一个对象作为一个参数被传递,通过访问这个对象可以获得参数的属性,将调用这个操作符的对象可以通过使用 this 操作符获得,下面这个例子展示了这一点:
#include<bits/stdc++.h>
using namespace std;
class Box
{
public :
double getVolume(void)
{
return length * breadth * height;
}
void setLength(double len)
{
length = len;
}
void setBreadth(double bre)
{
breadth = bre;
}
void setHeight( double hei )
{
height = hei;
}
Box operator + (const Box &other)//第一种重载方式
{
Box box;
box.length = this->length + other.length;
box.breadth = this->breadth + other.breadth;
box.height = this->height + other.height;
return box;
}
public:
double length;
double breadth;
double height;
};
Box operator + (const Box &ths, const Box &other)//第二种重载方式
{
Box box;
box.length = ths.length + other.length;
box.breadth = ths.breadth + other.breadth;
box.height = ths.height + other.height;
return box;
}
int main()
{
Box Box1, Box2, Box3;
double volume = 0;
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
cout << "Volume of Box3 : " << volume <<endl;
return 0;
}
上面的代码编译和执行时,它产生以下结果:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
可重载/不可重载的运算符
下面这张表列举了可以重载的运算符:
+ | - | * | / | % | ^ |
& | | | ~ | ! | , | = |
< | > | <= | >= | ++ | -- |
<< | >> | == | != | && | || |
+= | -= | /= | %= | ^= | &= |
|= | *= | <<= | >>= | [ ] | () |
-> | ->* | new | new[ ] | delete | delete[ ] |
下面这张表列举了不可以重载的运算符:
:: | .* | . | ?: |
运算符重载例子
这里有各种操作符重载的例子来帮助你理解这一概念。
序号 | 运算符和例子 |
---|---|
1 | 一元运算符重载 |
2 | 二元运算符重载 |
3 | 关系运算符重载 |
4 | 输入/输出运算符重载 |
5 | ++ 和 -- 运算符重载 |
6 | 赋值运算符重载 |
7 | 函数 call() 运算符重载 |
8 | 下标[ ]运算符重载 |
9 | 类成员获取运算符 -< 重载 |