簡體   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