错误C2440:' =' :无法转换为' int *'到' int **'

时间:2016-07-23 14:04:05

标签: c++ pointers

#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的二维数组中。我认为这是最有效的方法。现在我该如何解决这个错误?

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

需要

main = new T*[col];

因为main是指向T的指针数组。但是有更好的方法来创建二维数组,例如

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

答案 2 :(得分:0)

答案在您的上一个代码行中:

main[i]=new T[row];

为了实现这一点,main[i]需要成为一个指针。但您尝试将main创建为new T[col] - T的数组。它需要是一个指针数组 - T

main = new T*[col]; // Create an array of pointers