2017-09-26 137 views
0

我正在C++中制作一个模板化的矩阵类。为了创建这个类,我创建了一个指针数组,这些指针指向动态数组。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

让您的生活更轻松,只需使用'std :: vector'而不是指针和原始内存管理。 – PaulMcKenzie

+0

谢谢。从概念上讲,我正在尝试使用动态分配的数组来实现吗? – AustinGlad

+0

当然这是可能的。矢量如何在内部工作?它与你想要做的没有什么不同,只是更安全。其次,你的目标是开发一个Matrix类或者动态数组管理吗?如果要开发Matrix类,那么使用'vector'就可以开始开发Matrix类的实际工作。 – PaulMcKenzie

回答

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