C++ 重载运算符和重载函数:
C++
允许在同一作用域中的某个函数和运算符指定多个定义,分别称为函数重载和运算符重载。
重载声明是指一个与之前已经在该作用域内声明过的函数或方法具有相同名称的声明,但是它们的参数列表和定义(实现)不相同。
当您调用一个重载函数或重载运算符时,编译器通过把您所使用的参数类型与定义中的参数类型进行比较,决定选用最合适的定义。选择最合适的重载函数或重载运算符的过程,称为重载决策。
C++ 中的运算符重载
您可以重定义或重载大部分 C++
内置的运算符。这样,您就能使用自定义类型的运算符。
重载的运算符是带有特殊名称的函数,函数名是由关键字 operator
和其后要重载的运算符符号构成的。与其他函数一样,重载运算符有一个返回类型和一个参数列表。比如:
1 | Box operator+(const Box&); |
声明加法运算符用于把两个 Box 对象相加,返回最终的 Box 对象。大多数的重载运算符可被定义为普通的非成员函数或者被定义为类成员函数。如果我们定义上面的函数为类的非成员函数,那么我们需要为每次操作传递两个参数,如下所示:
1 | Box operator+(const Box&, const Box&); |
重载操作符的注意事项:
- 重载操作符时,必须有一个类型是类类型,不允许重载
c++
的内置类型(比如不能重载的两个参数都是int
); - 重载操作符不会改变操作符的优先级(比如先做乘除后加减),也不会改变结合性;
- 重载的操作符也不会进行短路计算(逻辑
&
和逻辑||
是具有短路功能的,重载之后就不再具有短路功能,一般情况下不要重载这些操作符); - 对操作符进行重载的函数可以作为成员函数也可以作为非成员函数,一般情况下,把算术操作(加减乘除)和关系操作(大于,小于…)作为非成员函数,把赋值操作作为成员函数;定义时把非成员函数定义为友元,这样才可以去操作私有的数据;
- 可以像函数调用一样去调用重载操作符的函数,比如
item1+item2
和operator+(item1,item2)
实现的效果是相同的。但是一般使用item1+item2
。 - 一个类如果要放在容器中,比如向量,就需要重载小于
<
,等于==
操作符。一般重载了==
操作符,就需要重载!=
操作符。同时,一般重载了<
操作符,就需要重载>,>=,<=
操作符,四个都要重载,不能只重载一个。 - 有4个操作符如果要重载就必须定义为成员函数,这四个操作符是:赋值操作符
operator=
,下标操作operator[],函数调用operator()
,成员访问operator->
。这四个操作符的重载绝对不能定义为非成员函数。其他操作符可以选择定义为成员函数还是非成员函数。一般把++
,--
和解引用*
定义为成员函数,但是算术操作符(加减乘除),关系操作符(大于小于这些),位操作符定义为非成员函数。 - 不能重载的操作符(4个):
::
.*
.
?:
代码涉及内容:
- 可以重载的操作符(42个):
+
-
*
/
&
|
… - 不能重载的操作符(4个):
::
.*
.
?:
- 重载操作符的注意事项
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
using namespace std;
class Person
{
// 重载操作符:加法
public:
// 注意:1.传入的应该是引用;2.传入参数写一个就行,第一个默认在this指针中;
void operator+(const Person& rhs)
{
cout << "执行了重载的加法操作" << endl;
}
};
int main()
{
int a, b;
a = 12;
b = 9;
cout << a + b << endl;
Person p1, p2;
p1 + p2;
cout << "Hello HTL2018" << endl;
return 0;
}代码执行结果:
参考链接:
C++ 重载运算符和重载函数