user4557113
user4557113

Reputation:

Overloading operators in C++ arrays

I'm relatively new to C++, thus the question. I'm trying to overload () operator for read and write operations in an array. This is a row-major array which maps a two -dimensional array to a one dimension.

This is the overload that I've written for read operations

//overloading read operator
    const double& operator()const(int n, int m){
      return arr_[n*column+m];
    }

Now I need to write a write overload that inserts a double value in the position returned by the read overload.

//overloading write operator
    double& operator()(double d){

    }

How exactly can I do that. Any help appreciated.

Upvotes: 3

Views: 233

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254771

The overload itself wouldn't insert anything; it would return a (non-const) reference which you can use to assign to an array element. The overload would be the same as your const overload (which you still need in addition to this one, to access constant objects), but without any const:

double& operator()(int n, int m){
  return arr_[n*column+m];
}

used thusly

array(2,3) = 42;

Upvotes: 5

Related Questions