Reputation: 21
I'm trying to implement overloading of the subscript operator in my doubly linked list class, but I am facing problems I've been unable to overcome by myself. I am also pretty new to C++.
This is what I have now.
Outtake from DList class:
T &operator[](int index) {
lookAt = root;
for (size_t i = 0; i < index; i++) {
lookAt = lookAt->getNext();
}
return lookAt->getItem();
}
Node<T>* root;
Node<T>* lookAt;
Node<T>* temp;
Node class:
template <class T>
class Node {
public:
Node() {
this->setNext(nullptr);
this->setPrev(nullptr);
}
Node *getNext() const {
return next;
}
void setNext(Node *next) {
Node::next = next;
}
Node *getPrev() const {
return prev;
}
void setPrev(Node *prev) {
Node::prev = prev;
}
T getItem() const {
return item;
}
void setItem(T item) {
Node::item = item;
}
private:
Node* next;
Node* prev;
T item;
};
The error I keep getting is this: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'int' return lookAt[index].getItem();
Which leads me to believe there's some kind of problem with the way my item variable is referenced, or/and the return part of the overloading function.
Would appreciate any help/guidance with this.
Cheers
Upvotes: 0
Views: 1041
Reputation: 3460
Your getItem() returns a T-type variable, which is a copy of the real data, item. (rvalue)
Your [] operator tries to return an T&, which is an lvalue (reference). However, we can't transform rvalue into lvalue.
One possible solution is to return T& in getItem(), like this:
T& getItem() {
return item; // Now returns a reference (lvalue).
}
Hope it helps.
Upvotes: 0