【问题标题】:Program stuck after compilation when trying to acsses private multy-dimensional array [duplicate]尝试访问私有多维数组时程序在编译后卡住[重复]
【发布时间】:2019-04-06 16:23:14
【问题描述】:

代码编译 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

【问题讨论】:

  • 您的构造函数似乎声明了int **arr,而不是访问成员变量。另外,您分配的是整数数组而不是 T。
  • 你应该只声明一次,作为私有变量。构造函数应该初始化那个指针,所以是的 - arr = new T*[...] 应该可以工作。如果你想更明确一点,可以使用this-&gt;arr = new ...
  • 我不知道我怎么没注意到...非常感谢。

标签: c++ oop templates multidimensional-array private


【解决方案1】:

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

【讨论】:

  • 我不知道我怎么没注意到...非常感谢。
猜你喜欢
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 2021-08-19
  • 1970-01-01
  • 2023-03-12
相关资源
最近更新 更多