2016-05-29 37 views
0

我有一個matrix類,並希望這樣做此操作:操作[] []過載 - 改變價值

matrix m1(2,4);  //creates matrix of size 2,4 full of 1's 
m1[1][2]=4;   //I wish the value in place m1- row 1 col 2 will be 4 

這是例子,我的代碼是如何writen(在本網站TY塞斯·卡內基發現!!)

class matrix{ 
public: 
    matrix() { 
     _arrayofarrays = new int*[10]; 
     for(int i = 0; i < 10; ++i) 
      _arrayofarrays[i] = new int[10]; 
    } 

    class Proxy { 
    public: 
     Proxy(int* _array) : _array(_array) { } 

     int operator[](int index) { 
      return _array[index]; 
     } 
    private: 
     int* _array; 
    }; 

    Proxy operator[](int index) { 
     return Proxy(_arrayofarrays[index]); 
    } 

private: 
    int** _arrayofarrays; 
}; 

問題是:M1 [2] [4]返回int和offcorce如果我恰克返回值不改變的M1值

我如何能做到這一點,因此價值會改變嗎? (也許返回INT &什麼?)

+0

當你嘗試過什麼事回報int&? –

+0

請看看[this](https://isocpp.org/wiki/faq/operator-overloading#matrix-array-of-array)。 –

回答

1

代替int