c++ - Is it possible to use the modified returned reference in an overload like `int &operator[]'? -
suppose have class implements array of int grows on demand. class implements int &operator[] method overloading [] operator , returning reference value in array.
now use operator in loop this
classinstance[index] += 1; i want know whether it's possible use incremented value inside int &operator[] function?
to make clear, want able know new value of referenced integer in order upadte maximum , minimum values.
the way solve problem return pretends int&, while providing overloads methods operator+=, etc.
something this:
class myintreference { public: myintreference(int& reference_to_wrap) : wrapped_reference_{reference_to_wrap} {} // method returns void, have return whatever want void operator+=(const int addend) { wrapped_reference_ += addend; dowhateveryouwant(); } private: int& wrapped_reference_; } // then, in other class myintreference yourotherclass::operator[](const int index) { return myintreference{my_array_[index]}; } obviously, rough piece of code, think refined quite nice.
Comments
Post a Comment