超负荷指标

来源:互联网 发布:绘画书籍推荐 知乎 编辑:程序博客网 时间:2024/05/01 13:34

产生的结果

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()
classMatrix
{
private:
    doubleadData[4][4];
public:
    Matrix()
    {
        // Set all elements of the matrix to 0.0
        for(intnCol=0; nCol<4; nCol++)
            for(intnRow=0; nRow<4; nRow++)
                adData[nRow][nCol] = 0.0;
    }
 
    double& operator()(constint nCol, constint nRow);
    voidoperator()();
};
 
double& Matrix::operator()(constint nCol, constint nRow)
{
    assert(nCol >= 0 && nCol < 4);
    assert(nRow >= 0 && nRow < 4);
 
    returnadData[nRow][nCol];
}
 
voidMatrix::operator()()
{
    // reset all elements of the matrix to 0.0
    for(intnCol=0; nCol<4; nCol++)
        for(intnRow=0; nRow<4; nRow++)
            adData[nRow][nCol] = 0.0;
}
这是我们的新的例子
1
2
3
4
Matrix cMatrix;
cMatrix(1, 2) = 4.5;
cMatrix();// erase cMatrix
std::cout << cMatrix(1, 2);

结果副车架

0

因为()操作符tempting如此灵活,它可以使用它的许多不同的用途。然而,这强烈劝阻,因为(我)不下载的象征指标“操作符”。在我们上面的例子这将是更好的,有擦除的功能作为一个功能叫做clear()或(),cmatrix.erase erase)是更容易明白cmatrix)(可以什么。。。。。。。

运算符()是常用的参数有两超负荷指标检索多维数组,一维数组A subset ofa返回所有元素的参数参数12)。别的东西更好的书面作为一个成员函数有一个更多的描述性名称。

维基百科更多的信息关于函子任何人学习更多关于他们的兴趣

我的理解是,函子的基本思想是,而不是通过一个函数指针的函数做一个具体的工作,你的一个重载的通过一个类()运算符来做同样的工作。这里的优势在于,类可以存储有关事物的状态信息函数不能

超载()做函子是一个先进水平的C + +的概念,所以别担心如果你只是学习语言。


0 0
原创粉丝点击