3

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.

5
  • "...inserts a double value in that position" What position? Your write operator defines only a double value, not a position. Commented Feb 17, 2015 at 16:06
  • @zenith in the position returned by the read overload Commented Feb 17, 2015 at 16:09
  • Do exactly the same, but remove the consts and you can say data(x,y) = 0;. Commented Feb 17, 2015 at 16:10
  • @molbdnilo but the row and column is not defined in the write overload. I'm not getting the correct signature. Commented Feb 17, 2015 at 16:12
  • BTW, you've placed the const in the wrong place in your existing code, member modifiers (cv-qualifier-seq) go after the argument list. Commented Feb 17, 2015 at 16:14

1 Answer 1

5

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.