Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        5年前关闭。
                                                                                            
                
        
我创建了一个名为ArrayCreator的类来动态分配2D数组。但是,当我运行main.cpp以输出2D数组的特定元素时,编译器将显示以下错误消息:


  错误:“ operator []”不匹配(操作数类型为“ ArrayCreator”和“ int”)


有关详细信息,请参见以下代码:

main.cpp:

#include <iostream>
#include "arraycreator.h"

using namespace std;

int main()
{
    ArrayCreator arr;
    arr.initArray();
    cout<<arr[4][5]<<endl;
    return 0;
}

---------------------------------------------------------

Header File:

#ifndef ARRAYCREATOR_H
#define ARRAYCREATOR_H
#define row 4
#define col 10

class ArrayCreator
{
    int** arr;
public:
    ArrayCreator();
    void initArray();
    ~ArrayCreator();
};

#endif // ARRAYCREATOR_H

---------------------------------------------------------

Implementation File:

#include "arraycreator.h"
#include <iostream>
using namespace std;

ArrayCreator::ArrayCreator(){
    arr=new int*[row];
    for(int i=0; i<row; i++){
        arr[i]=new int[col];
    }
}

ArrayCreator::~ArrayCreator(){
    for(int i=0; i<row; i++) {
        delete [] arr[i];
        arr[i]=NULL;
    }
    delete [] arr;
    arr=NULL;
}

void ArrayCreator::initArray(){
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            arr[i][j]=i*j;
        }
    }
}
---------------------------------------------------------

最佳答案

您需要公开移动成员arr并像这样使用它:arr.arr[1][1]或为ArrayCreator定义operator[](int)

int* operator[](int index)
{
  return arr[index];
}

10-08 11:23