尝试访问私有多维数组时,程序在完成后卡住[重复]

问题描述 投票:-2回答:1

这个问题在这里已有答案:

代码编译完成后,当程序试图访问私有数组时,它被卡住了。我构建一个构造函数,在这个函数中,我可以打印数组,但之后,如果我试图从另一个函数访问该数组,它无法正常工作。

在这段代码中它在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
c++ oop templates multidimensional-array private
1个回答
0
投票

你的问题是你在构造函数中重新声明成员变量“arr”,这导致了段错误。

© www.soinside.com 2019 - 2024. All rights reserved.