C ++模板类指向数组的指针动态数组

时间:2017-09-26 02:00:55

标签: c++ matrix dynamic-arrays template-classes arrayofarrays

我正在用C ++制作模板化矩阵类。为了创建这个类,我创建了一个指针数组,这些指针指向动态数组。

到目前为止,我有:

    template<typename T> class Matrix
    {
    public:
        //constructor
        int **m = new int*[_rows];
        for (int i = 0; i < _rows; i++)
        {
             m[i] = new int[_cols];
        }

        //destructor
        for (int i = 0; i < _rows; i++)
        {
            delete[] m[i]
        }
        delete[] m;
    };

我还想创建一些函数来操作这个结构。 我已经看到类似于此的代码使用了很多,但我没有看到这是如何创建一个包含指向其他数组的指针的数组。这个概念让我很困惑,我希望有人向我澄清我应该怎样做我想做的事情。

我希望这个类被隔离,而不是与输入有任何关系。它可能会在其他代码中调用,并使用我的函数来创建矩阵结构。创建一个指针数组对我来说不是一个令人困惑的部分,它使这些指针指向其他数组,并且指针数组的大小会根据输入条目的数量而增加。

1 个答案:

答案 0 :(得分:0)

#include <iostream>

using namespace std;

template<typename T> class Matrix
{
public:
    Matrix(int row, int col)
    {
        _rows = row;
        _cols = col;
        m = new T*[_rows];
        for (int i = 0; i < _rows; i++)
        {
            m[i] = new T[_cols];
            for(int j=0; j < _cols; j++)
            {
                m[i][j] = i*10 + j;
            }
        }
    }

    ~Matrix()
    {
        for (int i = 0; i < _rows; i++)
        {
            delete[] m[i];
        }
        delete[] m;
    }

    T **m;
    int _rows;
    int _cols;
};

void main()
{
    Matrix<int> a(3,4);

    for(int i=0; i<a._rows; i++)
    {
        for(int j=0; j<a._cols; j++)
        {
            cout << "[" << i << "][" << j << "]" << a.m[i][j] << " ";
        }
        cout << endl;
    }

}

结果:

[0] [0] 0 [0] [1] 1 [0] [2] 2 [0] [3] 3

[1] [0] 10 [1] [1] 11 [1] [2] 12 [1] [3] 13

[2] [0] 20 [2] [1] 21 [2] [2] 22 [2] [3] 23

相关问题