2016-07-23 102 views
0
#ifndef _grid_h 
#define _grid_h 

#include<string> 

using namespace std; 

template<typename T> 
class grid{ 
    T** main; 

public: 

    grid<T>(){} 


    grid<T>(int col, int row){ 
     main = new T[col];   //<-this line gives me error C2440: 
            //'=' : cannot convert from 'int *' to 'int **' 
     for(int i =0;i<col;i++) 
      main[i]=new T[row]; 
    } 
}; 

#endif 

我想创建自己的Grid类版本。基本上我想将信息保存在T的二维数组中。我认为这是最有效的方法。现在我怎样才能解决这个错误?错误C2440:'=':无法从'int *'转换为'int **'

回答

0

这将需要是

main = new T*[col]; 

由于main是一个指针到T阵列。但也有更好的方法来创建一个二维数组,例如

std::vector<std::vector<T>> main(col, std::vector<T>(row)); 
0

分配正确类型的数组:使用main = new T*[col];而不是main = new T[col];

0

答案是你最后的代码行:

main[i]=new T[row]; 

对于工作,main[i]需要一个指针。但是您尝试创建main作为new T[col] - 一组T s。它需要是一个指针数组 - T

main = new T*[col]; // Create an array of pointers 
相关问题