简体   繁体   中英

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM