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
getItem()needs to be changed to returnT&, oroperator[]needs to returnT, or the latter needs to be implemented without using the former. Actually, you probably want two overloads ofgetItem()- a non-const one returningT&, and a const one returning eitherTorconst T&.lookAtandtempare member variables instead of local variables.