Dereferencing the void pointer in C++

后端 未结 4 2142
南方客
南方客 2020-12-20 06:11

I\'m trying to implement a generic linked list. The struct for the node is as follows -

typedef struct node{
        void *data;
        node *next;      
};         


        
4条回答
  •  萌比男神i
    2020-12-20 06:54

    A void pointer cannot be dereferenced. You need to cast it to a suitable non-void pointer type. The question is about C++ so I suggest considering using templates to achieve your goal:

    template  struct node
    {
       T *data;
       node *next;      
    };
    

    then:

    int n1=6;
    node *temp = new node();
    temp->data=&n1;
    

    And finally:

    cout << (*(temp->data));
    

    Typecasting is possible, but that will be a C-style type-unsafe solution and not a C++ one.

提交回复
热议问题