How to do some stuff with values assigned in subscript operator?

孤者浪人 提交于 2019-12-13 06:41:19

问题


Suppose i've data array 0,0,1,1,2,2,5,5,7,7,2,2 as data member in class and i want to define subscript operator in such they

[i] returns me 2*i element of array but also i want let user to set elements, so

[i] = n, must be applied to both 2*i and 2*i+1.

Is it possible to do it with showing to user only subscript operator?

0,0,1,1,2,2,5,5,7,7,2,2
[3] = 4;
0,0,1,1,2,2,4,4,7,7,2,2

another workarounds? and in general it may be not only two elements.


回答1:


Indirectly, yes.

You can return a dedicated type with the subscript operator that works basically like a functor and takes care of assigning the value according to your specification:

struct AssignFunctor {
  MyArrayType& parent;
  size_t index;
  AssignFunctor(MyArrayType& parent, size_t index) : parent(parent), index(index) {}
  AssignFunctor& operator=(int k) {
    parent.set(index,k);
    parent.set(index*2,k);
  }
  operator int() const {
    return parent.get(index);
  }
};

struct MyArrayType {
  AssignFunctor operator[](size_t index) {
    return AssignFunctor(*this,index);
  }
  int operator[](size_t index) const {
    return get(index);
  }
  void set(size_t,int);
  int get(size_t) const;
};



回答2:


I am pretty sure you can implement it as mentioned above. But there's a ground rule for operator overloading. Don't change the meaning of the operator

In the user's perspective you're setting one element but that is applied to a different one as well. Better give meaningful function or change the design of your data structure.



来源:https://stackoverflow.com/questions/12249565/how-to-do-some-stuff-with-values-assigned-in-subscript-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!