我在使用 const 版本重载 operator() 时遇到问题:
#include <iostream>
#include <vector>
using namespace std;
class Matrix {
public:
Matrix(int m, int n) {
vector<double> tmp(m, 0.0);
data.resize(n, tmp);
}
~Matrix() { }
const double & operator()(int ii, int jj) const {
cout << " - const-version was called - ";
return data[ii][jj];
}
double & operator()(int ii, int jj) {
cout << " - NONconst-version was called - ";
if (ii!=1) {
throw "Error: you may only alter the first row of the matrix.";
}
return data[ii][jj];
}
protected:
vector< vector<double> > data;
};
int main() {
try {
Matrix A(10,10);
A(1,1) = 8.8;
cout << "A(1,1)=" << A(1,1) << endl;
cout << "A(2,2)=" << A(2,2) << endl;
double tmp = A(3,3);
} catch (const char* c) { cout << c << endl; }
}
这给了我以下输出:
- 调用了 NONconst-version - - 调用了 NONconst-version - A(1,1)=8.8
- 调用了 NONconst-version - 错误:您只能更改矩阵的第一行。
如何实现 C++ 调用 operator() 的 const 版本?我正在使用 GCC 4.4.0。