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;
}
You overloaded
operator=
for theArray
class, not forint
(which you can't do, by the way).x[1]=5;
is usingArray::operator[]
for element access, which returns anint&
, and then uses the normalint
assignment operator for the=5
part.Array::operator=
is only used when you're assigning to the whole object (i.e. the way you've defined it, you can dox = 5;
), not to its elements/members.The assignment operator you wrote would apply to an array, not an array element. For example
would use your assignment operator. From the looks of it you want to have an overloaed assignment operator applied when using the subscript operator. The only way to get something like this to work is using a proxy class:
It does not use your
operator=
because you are not assigning to an instance ofArray
, you're assigning to anint
. This would invoke your 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:What do you want the
operator=
to do? I would suggest a better signature isand it should (i) return a self-reference
*this
, and (ii) should do a better job of re-initializing other values, i.e. it might make more sense to clear your array or do something like that.Runnable source code at: http://ideone.com/ejefcr
Here is the output. Format for the printing is
(one, two, ptr[0])
. I guess you want the member variableone
to be the index of the last-accessed element?If you remove the overloading of the
=
operator in your code, then you'll already have the behaviour you're desiring, since your overloaded[]
operator returns a reference to the list item. For example:Output:
If I were being careful, I would also include error handling for the case where I try and $L[i]$ and element outside of the array length.