2016-07-23 182 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 
相關問題