use*_*763 4 c++ overloading operator-overloading subscript assignment-operator
我重载了下标运算符和赋值运算符,我试图Array x;
x[0]=5;
通过重载下标运算符来获得赋值运算符示例的正确值,
我可以获得值 0,但是当我重载赋值运算符时,它会进行赋值,但它不使用我的重载函数,因为可用2 的值应该是 5。
class Array
{
public:
int *ptr;
int one,two;
Array(int arr[])
{
ptr=arr;
}
int &operator[](int index)
{
one=index;
return ptr[index];
}
int & operator=(int x){
two=x;
return x;
}
};
int main(void)
{
int y[]={1,2,3,4};
Array x(y);
x[1]=5;
cout<<x[0]<<endl;
}
Run Code Online (Sandbox Code Playgroud)
它不使用 youroperator=因为您没有分配给 的实例Array,而是分配给int. 这将调用您的操作员:
Array x;
x = 7;
Run Code Online (Sandbox Code Playgroud)
如果要拦截对operator[]返回内容的赋值,则必须让它返回一个代理对象并为该代理定义赋值运算符。例子:
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); }
};
Run Code Online (Sandbox Code Playgroud)