程序在编译后卡住,当试图 acsses 私有多维数组时
Program stuck after compilation when trying to acsses private multy-dimensional array
代码编译后,当程序试图访问私有数组时,它被卡住了。 我构建了一个构造函数,在这个函数中我可以打印数组,但之后如果 IM 尝试从另一个函数访问数组,它不起作用。
在此代码中,它在 mat(1,2( 上工作时卡住了 - 试图返回 arr[1][2]:
我试图以不同的方式分配数组,使 [] 运算符,但似乎没有任何效果。
主文件 :
#include "matrix.h"
#include <iostream>
int main() {
Matrix<4, 4> mat;
mat(1,2);
std::cout << mat << std::endl;
return 0;
}
.h 文件 :
#ifndef matrix_h
#define matrix_h
#include <iostream>
template <int row, int col ,typename T=int>
class Matrix {
public:
Matrix(int v = 0) { // constructor with deafault value of '0'
int **arr = new int*[row]; //initializing place for rows
for (int j = 0;j < row;j++) {
arr[j] = new int[col];
}
for (int i = 0;i < row;i++)
for (int j = 0;j < col;j++)
arr[i][j] = v;
}
T& operator () (int r, int c) const {
return arr[r][c];
}
friend std::ostream& operator<<(std::ostream& out,const Matrix <row,col,T> mat) {
for (int i = 0;i < row;i++) {
for (int j = 0;j < col;j++) {
out << mat(i,j) << " ";
}
out << std::endl;
}
return out;
}
private:
T** arr;
};
#endif //matrix_h
你的问题是你在构造函数中重新声明成员变量"arr",这导致了段错误。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '