2014-12-04 101 views
0

我有問題初始化多維數組元素。初始化多維數組元素

這裏是我的代碼:

class A{ 
    int *const e; 
    const int row, column; 
public: 
    A::A(int r, int c) : row(r), column(c), e(new int[r*c]) 
    { 
     for (int i = 0; i < r*c; i++) 
     { 
      e[i] = 0; 
     } 
    } 

    A(const A &matrix) : row(matrix.row), column(matrix.column) ,e(new int[matrix.row*matrix.column]) 
    { 
     for (int i = 0; i < matrix.row*matrix.column; i++) 
     { 
      e[i] = matrix.e[i]; 
     } 
    } 
    virtual ~A()  //destructing a A 
    { 
     delete[] e; 
    } 
}; 

但是,當我試圖初始化多維數組的元素,我得到了一個錯誤:

int main(int argc, char* argv[]) 
{ 
    A c(2, 5); 
    c[0][0] = 1; 
    A a(c); 
    return 0; 
} 

1 IntelliSense: no operator "[]" matches these operands operand types are: MAT [ int ]

編輯: 根據意見我嘗試寫運算符[]

virtual int *const operator[ ](int r) 
{ 
    return e[r][0]; 
} 

它應該獲得第r行的第一個元素。但我有一個錯誤:

1 IntelliSense: expression must have pointer-to-object type

+2

'A'的第二元件如果你想使用它,需要一個'operator []'。 – 2014-12-04 04:04:57

回答

0

你試圖將[]適用於A類,C++只知道如何使用操作[]陣列上。爲了使用他們爲你必須告訴如何[]作品A,所以你的類定義中,你應該把:

int *operator[](int x){ 
    return &e[x*row]; 
} 

它基本上接受你已經把括號中的編號,並返回相應的行(陣列),這樣就可以應用[]再次容易,因此,例如:

c[0]返回第一行

c[0][1]訪問第一行