c++ - 重载函数调用 operator() 用于模板对象的索引和赋值
问题描述
我正在尝试为矩阵数据结构创建一个模板,并且我希望以简洁直观的方式来索引和分配元素(即'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;
}
当我尝试使用显式类型的结构(在本例中为 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.
}
有用的链接:如何调试小程序
PS正确的索引是i*(this->cols) + j
.
推荐阅读
- amazon-web-services - aws cli ec2 describe 命令什么都不返回
- angular - 多个 401 Angular 令牌拦截器
- java - 字符串到房间数据库中的 int
- java - MultipartFormDataOutput 中的缺失部分取决于键的顺序
- javascript - React 组件在加载时“闪烁”,因为状态被覆盖
- sql - 对数字系列进行四舍五入以获得尽可能多的“四舍五入”数字,总和为 100
- frontend - 如何制定 sigma 规则来跟踪应用程序的行为
- reactjs - React js 导出一个变量
- postgresql - 具有字符集编码的 postgresql http 请求
- opencv - 如何创建球形图像?