c++ - How to control value assigned by operator [] -
i know how overload operator[]
follows :
t& operator [](int idx) { return thearray[idx]; } t operator [](int idx) const { return thearray[idx]; }
but want control values assigned arr[i] = value
. want control value between 0 , 9. there syntax so?
rene has provided answer. in addition this, here full example. note added "user-defined conversion", i.e., operator t
, in proxy_t
class.
#include <iostream> #include <array> #include <stdexcept> template <class t> class myclass { std::array<t, 5> thearray; // array... class proxy_t { t& value; // reference element modified public: proxy_t(t& v) : value(v) {} proxy_t& operator=(t const& i) { if (i >= 0 , <= 9) { value = i; } else { throw std::range_error(std::to_string(i)); } return *this; } operator t() // required getting t value proxy_t, make cout-lines work { return value; } }; public: proxy_t operator [](int const idx) { return thearray.at(idx); } t operator [](int const idx) const { return thearray[idx]; } }; int main() { myclass<int> a; std::cout << a[0] << std::endl; a[0] = 2; std::cout << a[0] << std::endl; a[1] = 20; }
Comments
Post a Comment