产生的结果:
4.5
现在,让我们超负荷()操作符,这个时间的方式,不带参数,在所有的
|
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
31
32
33
|
#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); void
operator()();};double&
Matrix::operator()(const
int
nCol, const
int
nRow){ assert(nCol
>= 0 && nCol < 4); assert(nRow
>= 0 && nRow < 4); return
adData[nRow][nCol];}void
Matrix::operator()(){ //
reset 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;} |
|
1
2
3
4
|
Matrix
cMatrix;cMatrix(1,
2) = 4.5;cMatrix();
//
erase cMatrixstd::cout
<< cMatrix(1, 2); |
结果:副车架。
0
因为()操作符tempting如此灵活,它可以使用它的许多不同的用途。然而,这强烈劝阻,因为(我)不下载的象征指标“操作符”。在我们上面的例子,这将是更好的,有写在擦除的功能作为一个功能叫做clear()或(),为cmatrix.erase erase()是更容易明白比cmatrix()(可以做什么!)。。。。。。。
运算符()是常用的参数有两个超负荷指标和检索多维数组,一维数组A subset ofa(返回所有元素的参数从参数1和2)。别的东西是更好的书面作为一个成员函数有一个更多的描述性名称。
维基百科有更多的信息关于函子,任何人在学习更多关于他们的兴趣。
我的理解是,函子的基本思想是,而不是通过一个函数指针的函数做一个具体的工作,你的一个重载的通过一个类()运算符来做同样的工作。这里的优势在于,类可以存储有关事物的状态信息,而函数不能。
超载()做函子是一个先进水平的C + +的概念,所以别担心如果你只是学习语言。:)
本文深入探讨了C++运算符()的多种用途及其与函子概念的关系,强调了避免使用操作符作为参数传递的建议,并通过实例展示了如何更清晰地实现类的方法。
524

被折叠的 条评论
为什么被折叠?



