所有的重载操作符,你见过到目前为止让你定义的操作符的形参的类型,但参数的数目是固定的基于经营者的类型。例如,= =运算符总是有两个参数,而不是总是一个逻辑算子。括号(())是一个特别有趣的算子,它可以让你不同的类型和参数,它需要数!
有两件事情要记住:第一,括号操作符必须为成员函数的实现。第二,在非类C++的,()运算符用于调用函数或写表达式评估优先级较高的。对运算符重载的情况下,在()操作符没有-相反,它只是一个正常的操作调用的函数(称为operator())像其他重载操作符。
让我们以一个常见的例子,适合重载操作一看:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class
Matrix { private : double
adData[4][4]; public : Matrix() { //
Set all elements of the matrix to 0.0 for
( int
nCol=0; nCol<4; nCol++) for
( int
nRow=0; nRow<4; nRow++) adData[nRow][nCol]
= 0.0; } }; |
矩阵是线性代数的一个重要组成部分,常被用来做几何建模和三维计算机图形的工作。在这种情况下,所有你需要知道的是,矩阵类是由一个4双打4的二维数组。
在课上,重载的下标操作符,你知道我们可以重载运算符[]向私人的一维数组提供直接访问。然而,在这种情况下,我们希望获得一个私人的二维数组。因为操作符[]只有一个参数,足以让我们指数的一个二维数组不。
然而,由于()运算符可以采取许多参数,我们想,我们可以声明一个版本的operator()接受两个整数,用它来访问我们的二维数组。这里是一个例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#include
<cassert> // for assert() class
Matrix { private : double
adData[4][4]; public : Matrix() { //
Set all elements of the matrix to 0.0 for
( int
nCol=0; nCol<4; nCol++) for
( int
nRow=0; nRow<4; nRow++) adData[nRow][nCol]
= 0.0; } double &
operator()( const
int
nCol, const
int
nRow); }; double &
Matrix::operator()( const
int
nCol, const
int
nRow) { assert (nCol
>= 0 && nCol < 4); assert (nRow
>= 0 && nRow < 4); return
adData[nRow][nCol]; } |
1
2
3
|
Matrix
cMatrix; cMatrix(1,
2) = 4.5; std::cout
<< cMatrix(1, 2); |