It does not use your operator=
because you are not assigning to an instance of Array
, you're assigning to an int
. This would invoke your operator:
Array x;
x = 7;
If you want to intercept assignments to what operator[]
returns, you must have it return a proxy object and define the assignment operator for that proxy. Example:
class Array
{
class Proxy
{
Array &a;
int idx;
public:
Proxy(Array &a, int idx) : a(a), idx(idx) {}
int& operator= (int x) { a.two = x; a.ptr[idx] = x; return a.ptr[idx]; }
};
Proxy operator[] (int index) { return Proxy(*this, index); }
};
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…