简体   繁体   中英

why cannot we initialize a node without using a pointer?

I have recently started learning data structure and as a beginner, I have a query while implementing linked list nodes, why do we have to initialize node using a pointer only?

class node{
    public:
    int data;
    node* next;
    node(int val){
        data = val;
        next = NULL;
    }
 };
 int main(){
    node* head = NULL;
    node head = NULL; // this throws an error which i cannot understand
 }

Actually you can initialize the node by value. If you want to initialize a node with value, according to your constructor node(int val) , you have to code like below:

class node{
    public:
    int data;
    node* next;
    explicit node(int val){
        data = val;
        next = NULL;
    }
 };
 int main(){
    int value = 777;
    //node* head = NULL; // Initialize head pointers to null
    node head(value);   // By your constructor definition
 }

EDIT: By the way, marking a constructor as explicit is a very good habit to have, as it prevents unexpected conversion, as Duthomhas commented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM