Reputation: 5
I'm having issues with the overloaded + operator and the overloaded [] operator. The [] function works fine when used on the OrderedList right object but I cannot get it to return the correct value when used with the this pointer.
The way the code works in main is something like: list3 = list1 + list2
where list2 becomes 'right' in the parameter list, and I am trying to use the this pointer to get the value at the subscript for list1.
The error I'm getting is "cannot convert OrderedList to double in assignment" but I am unsure why it is trying to assign an OrderedList?
Any help much appreciated, thanks.
OrderedList OrderedList::operator+(OrderedList &right)
{
int size1 = this -> _size;
int size2 = right.getSize();
double x, y;
y = right[size2];
x = this[size1];
OrderedList list3;
return list3;
}
double OrderedList::operator[](int subscript) const // returns rvalue
{
int x = OrderedList::_size;
if (subscript > x)
{
cout << "Error: number is bigger than the size of the list" << endl;
}
else
{
Node* temporary = OrderedList::getListHead();
for (int counter = 1; counter < subscript; counter++)
{
temporary = temporary -> next;
}
double nodeValue = temporary -> item;
return nodeValue;
}
}
Upvotes: 0
Views: 64
Reputation: 9648
this
is a pointer so why you try to do this[size1]
it is doing pointer arithmetic. Think:
int a[] = {0, 1};
int *b[2] = &a;
To get to the actual data from b
we must derefence it first:
int c = (*b)[1];
Likewise here we must dereference this
:
x = (*this)[size1];
Upvotes: 3
Reputation: 234875
this->operator[](/*your parameters here*/)
will work.
You can drop this->
although it can make things less clear.
(this[size1]
will perform some nasty pointer arithmetic - equivalent to this + size1
: therefore almost certainly accessing memory you don't own).
Upvotes: 0