如何用下标运算符中分配的值来做一些事情? [英] How to do some stuff with values assigned in subscript operator?
问题描述
假设我将数据数组0,0,1,1,2,2,5,5,7,7,2,2作为类中的数据成员,而我想在此类数组中定义下标运算符
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]返回2 * i数组元素,但我也想让用户设置元素,所以
[i] returns me 2*i element of array but also i want let user to set elements, so
[i] = n,必须同时应用于2 * i和2 * i + 1.
[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.
推荐答案
间接,是的.
您可以使用下标运算符返回一个专用类型,该运算符的工作原理基本上类似于函子,并会根据您的规范分配值:
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;
};
这篇关于如何用下标运算符中分配的值来做一些事情?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!