Home > OS >  Unable to overload '[ ]' in here. C Noob here
Unable to overload '[ ]' in here. C Noob here

Time:02-17

I am trying to implement a linkedlist in C and trying to incorporate array like data access using '[]'.

First I declared a Node class as the following.

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

Then I implemented the Linkedlist class as the following where I have overloaded the '[]' operator like the following

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;
    }
};

In the main function I have tried to print the 'l[0]'. It shows error as

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

Please help me out. Am I missing some concept here ?

The main function :

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;
}

The getsize function :

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

CodePudding user response:

Since l is a pointer which is created by

LinkedList *l = new LinkedList();

it needs to be dereferenced to be able to use operator first.

This would solve your problem: cout << (*l)[0];

But I suggest you to not create LinkedList with new keyword so you can avoid using raw pointers and memory leaks in the application code. You could use LinkedList l; instead.

  • Related