Sti*_*RAN 0 c++ templates operator-overloading
我正在尝试为矩阵数据结构创建模板,并且我希望以简洁直观的方式来索引和分配元素(即 'A(i,j)' 返回一个元素和 'A(i,j)=x ' 为该元素分配一个值。)
根据其他论坛主题,我看到通过引用返回数组元素,函数/运算符可以以这种方式返回和更改该元素。
template <typename T, int Rows, int Cols>
struct Matrix {
private:
public:
const int rows = Rows; //number of rows
const int cols = Cols; //number of columns
T data[Rows*Cols]; //contents of matrix
//Single element indexing and assigment
T& operator() (int i, int j) {
return data[ (i-1)*(this->cols) + j ];
}
};
int main(){
const int m = 3;
const int n = 4;
Matrix<float, m, n> A;
for (int i = 0; i < A.rows; i++) {
for (int j = 0; j < A.cols; j++) {
A(i,j) = 3.14;
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用显式类型的结构(在本例中为 int)而不是模板时,这非常有效,但是现在我使用的是模板,赋值 'A(i,j) = x' 具有修改索引的效果'i' 和 'j' 通常会破坏循环并导致分段错误。
有谁知道为什么会发生这种情况,如果我能做些什么来达到预期的结果?
我对 C++ 相当陌生,所以如果我反对该语言的最佳实践,请随时告诉我
用于索引的公式data不正确。
更新您的函数以data[0]始终返回但打印索引。输出将清楚表明您没有使用正确的索引。
T& operator() (int i, int j) {
int index = (i-1)*(this->cols) + j;
std::cout << "Index: " << index << std::endl;
return data[0]; // This is wrong but that's not the
// purpose of this suggested change.
}
Run Code Online (Sandbox Code Playgroud)
有用链接:如何调试小程序
PS正确的索引是i*(this->cols) + j.