[英]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.