2016-05-29 12 views
0

Ich habe eine matrix Klasse und will diesen Vorgang tun:Operator [] [] Überlast - den Wert ändern

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 

dies ist beispielsweise, wie mein Code writen wird (auf dieser Seite ty gefunden Seth Carnegie !!)

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; 
}; 

das Problem ist: m1 [2] [4] gibt einen int und offcorce, wenn ich den zurückgegebenen Wert chage es nicht den m1 Wert ändert

wie kann ich es tun, so dass die Wert wird geändert? (Vielleicht int & oder etwas zurückgeben?)

+0

Was passiert, wenn man es versucht? –

+0

Bitte schauen Sie sich [this] an (https://isocpp.org/wiki/faq/operator-overloading#matrix-array-of-array). –

Antwort

1

Rückkehr int& statt int