现在我们可以声明一个矩阵和访问它的元素,像这样:
1
2
3
Matrix cMatrix;
cMatrix(1, 2) = 4.5;
std::cout << cMatrix(1, 2);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;
}产生的结果:
0
由于()运算符是非常灵活的,可以尝试使用它为许多不同的目的。然而,这是强烈反对的,因为()符号没有给任何指示,操作者是做什么。在上面的例子里,它会更好写擦除功能作为一个功能叫做clear()或erase(),为CMatrix。erase()比cmatrix()容易理解(可以做任何事情!)。
运算符()通常是超负荷的两个参数指标的多维数组,或检索的一一维数组的子集(返回所有元素从参数1参数2)。什么可能是更好的写作为成员函数与一个更具描述性的名称。
博客指出()运算符很灵活,但不建议随意使用,因其不能明确指示操作内容。如对于CMatrix,写擦除功能用clear()或erase()比cmatrix()更易理解。运算符()常用于多维数组指标或一维数组子集检索,建议写成有更具描述性名称的成员函数。
1163

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



