Overloading "[]" method in my LinkedList Class [closed]

  c++, linked-list, methods, operator-overloading
template <class T>
class SingleList {
public:
    SingleList() {
        head = tail = nullptr;
    }

    SingleList(std::initializer_list<T> elements) {
        head = tail = nullptr;
        for (auto element : elements) push_back(element);
    }
    void push_back(const T &data) {
        Node<T>* ptr;
        if (!head) {
            ptr = new Node<T>(data);
            head = ptr;
            tail = ptr;
            elementSize++;
        }
        else {
            Node<T>* temp = tail;
            ptr = new Node<T>(data);
            tail = ptr;
            temp->next = tail;
            tail->previous = temp;
            elementSize++;
        }
    }

    T& operator[](int idx) {
        Node<T>* ptr = head;
        for (int i = 0; i < idx; i++) {
            ptr = ptr->next;
        }
        return &(ptr->data);
    }
    int size() {
        return elementSize;
    }
private:
    Node<T>* head;
    Node<T>* tail;
    int elementSize = 0;
};

I have such a class and I am trying to overload operator[] but I couldn’t figure out how I can return the lvalue of specific position. I know that it should be reference but when I’m trying to do something like above I got:

Error   C2440   'return': cannot convert from 'T *' to 'T

To sum up, I want add an access element future like "myList[2] = 3".

Source: Windows Questions C++

LEAVE A COMMENT