简体   繁体   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

I want to create my own version of the Grid class. 我想创建自己的Grid类版本。 Basically I want to save the information in a 2 dimensional array of T. I think this is the most efficient way to do it. 基本上,我想将信息保存在T的二维数组中。我认为这是最有效的方法。 Now How can I get around this error? 现在如何解决该错误?

Allocate an array of correct type: use main = new T*[col]; 分配正确类型的数组:use main = new T*[col]; instead of main = new T[col]; 代替main = new T[col]; .

It would need to be 它需要是

main = new T*[col];

Because main is an array of pointers to T . 因为main是一个指向T的指针数组。 But there are better ways to create a two-dimensional array, for example 但是有更好的方法来创建二维数组,例如

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

The answer is in your last code line: 答案在您的最后一条代码行中:

main[i]=new T[row];

For that to work, main[i] needs to be a pointer. 为此, main[i]必须是一个指针。 But you tried to create main as a new T[col] - an array of T s. 但是您尝试将main创建为new T[col] T的数组。 It needs to be an array of pointers-to- T . 它必须是指向T的指针的数组。

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

暂无
暂无

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

相关问题 错误C2440:“返回”:无法从“ int [2]”转换为“ int(&amp;&amp;)[2]” - Error C2440: 'return' : cannot convert from 'int [2]' to 'int (&&)[2]' decltype 错误 C2440 无法从“int *”转换为“int *&amp;” - decltype error C2440 cannot convert from 'int *' to 'int *&' 错误C2440:“ =”:无法从“ int”转换为“ char [5]” - error C2440: '=' : cannot convert from 'int' to 'char [5]' 错误:C2440“返回”:无法从“int”转换为 T - error: C2440 'return': cannot convert from 'int' to T 错误c2440&#39;=&#39;无法从int *转换为Type <T> * - Error c2440 '=' cannot convert from int * to Type<T> * C2440&#39;=&#39;无法从&#39;int&#39;转换为&#39;BST <int> ::节点* - C2440 '=' cannot convert from 'int' to 'BST<int>::Node* 错误C2440:&#39;=&#39;:无法从&#39;char *(__ cdecl *)(int,int)&#39;转换为en&#39;GetItemText_t&#39; - error C2440: '=' : cannot convert from 'char *(__cdecl *)(int,int)' to en 'GetItemText_t' 错误C2440:&#39;初始化&#39;:无法从&#39;const int&#39;转换为&#39;int *&#39; - error C2440: 'initializing' : cannot convert from 'const int' to 'int *' 返回NULL但得到错误C2440:&#39;return&#39;:无法从&#39;int&#39;转换为&#39;const&&#39; - returning NULL but getting error C2440: 'return' : cannot convert from 'int' to 'const &' 如何修复错误 C2440: 'return': cannot convert from 'int' to 'elem *'? - How do I fix the error C2440: 'return' : cannot convert from 'int' to 'elem *'?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM