带下标运算符的重载赋值运算符 [英] overloading assignment operator With subscript operator
问题描述
我重载了下标运算符和赋值运算符,我正在尝试为赋值运算符获取正确的值例子数组 x;x[0]=5;
通过重载下标运算符,我可以获得值 0,但是当我重载赋值运算符时,它会进行赋值,但它不使用我的重载函数,因为变量 2 应该具有值 5.
I overloaded both subscript operator and assignment operator and I am trying to get right value to assignment operator
example
Array x;
x[0]=5;
by overloading subscript operator i can get value 0 but when i overload assignment operator it does the assignment but it doesn't use my overloaded function because vaiable 2 should have value 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;
}
推荐答案
它不使用你的 operator=
因为你没有分配给 Array
的实例,你'正在分配给 int
.这将调用您的操作员:
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;
如果您想拦截对 operator[]
返回的赋值,您必须让它返回一个代理对象并为该代理定义赋值运算符.示例:
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); }
};
这篇关于带下标运算符的重载赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!