vendredi 19 décembre 2014

c++ overload operator() for assigning value in a dynamic 2D array

I am trying to overload () operator to assign value into a dynamically allocated 2D array, here is my code --



class test {
private:
int** data ; int row, col ;

public:
test(int row = 2, int col = 2) {
this->row = row ; this->col = col ;
this->data = new int*[this->row] ;
for(int i = 0 ; i < this->row ; i++)
this->data[i] = new int[this->col] ;
}

~test() {
for(int i = 0 ; i < this->row ; i++)
delete [] this->data[i] ;
delete [] this->data ;
}

const int operator() (int row, int col) { // read operation
return this->data[row][col] ;
}

int& operator() (int row, int col) { // write operation
return this->data[row][col] ;
}

// for printing
friend ostream& operator<< (ostream &os, const test &t);
};


In the operator() write operation, I am trying to return the value by reference so that I can assign value like this --



test t(4,4) ;
t(2,2) = 5 ;


But it does not compile, says that I can't do such kind of overloading, any idea ?


Aucun commentaire:

Enregistrer un commentaire