c++ - 尝试访问私有多维数组时,程序在编译后卡住
问题描述
在代码编译 my 之后,当程序试图访问私有数组时,它被卡住了。我构建了一个构造函数,在这个函数中我可以打印数组,但之后如果我试图从另一个函数访问数组,它就不起作用了。
在这段代码中,它在处理 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”,这导致了段错误。
推荐阅读
- java - 如何从 Android 应用程序调用部署到 Google Cloud Platform 上的功能?
- python - 实现 UI Tkinter 时遇到问题
- codeigniter-4 - 允许内存大小 Codeigniter 4
- google-kubernetes-engine - kubectl get all -n cass-operator 的输出中的 2/2 是什么意思
- php - Laravel HasOneThrough 关系
- python - 带有 Python 和高级计划的 Azure Functions:尽管版本为 3.8。选择 3.6。被部署
- reactjs - 如何使用 Apollo Client 虚拟字段
- docker - 主机操作系统:Windows10;Docker 来宾操作系统:Centos:latest;可以在此设置上执行 systemd 吗?
- svg - 如何缩放 SVG 文本可点击区域?
- velocity - 速度模板循环遍历数组以创建字符串