繁体   English   中英

错误C2440:“ =”:无法从“ int *”转换为“ int **”

[英]error C2440: '=' : cannot convert from 'int *' to 'int **'

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

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

它需要是

main = new T*[col];

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

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

答案在您的最后一条代码行中:

main[i]=new T[row];

为此, main[i]必须是一个指针。 但是您尝试将main创建为new T[col] T的数组。 它必须是指向T的指针的数组。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM