无法在此处重载“[]”。 C++ 菜鸟在这里

Unable to overload '[ ]' in here. C++ Noob here

我正在尝试在 C++ 中实现一个链表,并尝试使用“[]”合并类似数组的数据访问。

首先我声明了一个节点class如下。

class Node{
    public:
    int data;
    Node *next, *prev;
   
    Node(int val){
        this -> data = val;
        this -> next = NULL;
        this -> prev = NULL;
    }
};

然后我实现了 Linkedlist class 如下,我重载了 '[]' 运算符,如下所示

class LinkedList{
    public:
    Node *head;

    LinkedList(){
        this -> head = NULL;
    }

    LinkedList(Node *h){
        this -> head = h;
    }

    int operator [] (int index){
        if(index < 0 || index >= getsize(this -> head)){
            cout << "List out of bounds" << endl;
            return -1;
        }else{
            Node *cur = this -> getnode(index);
            return cur -> data;
        }
    }

    Node* getnode(int index){
        int count = 0;
        Node *cur = this -> head;
        while(cur != NULL){
            if(count == index)
                break;
            count++;
            cur = cur -> next;
        }
        return cur;
    }
};

在主函数中,我尝试打印 'l[0]'。它显示错误为

no operator "<<" matches these operandsC/C++(349)
linklist_sort.cpp(173, 10): operand types are: std::ostream << LinkedList

请帮帮我。我是不是漏掉了一些概念?

主要功能:

int main(){

    srand(time(0));
    LinkedList *l = new LinkedList();

    for(int i = 0; i<10; i++){
        int num = rand() % 50 + 1;
        l -> head = l -> insert(l->head,num);
    }

    l->printlist(l->head);

    int n1, n2;
    cout << "\n";
    cin >> n1 >> n2;
    l->swap(l->head,n1,n2);
    l->printlist(l->head);

    cout << "\n";
    cout << l[0]; //Error here
    return 0;
}

getsize 函数:

int getsize(Node *head){
        if(head == NULL)
            return 0;
        else
            return 1 + getsize(head->next);
}

因为 l 是一个由

创建的指针

LinkedList *l = new LinkedList();

需要取消引用才能首先使用运算符。

这将解决您的问题: cout << (*l)[0];

但我建议您不要使用 new 关键字创建 LinkedList,这样可以避免在应用程序代码中使用原始指针和内存泄漏。 您可以改用 LinkedList l;