Correct way of initializing a struct in a class constructor

前端 未结 5 612
灰色年华
灰色年华 2020-12-08 02:44

So I want to add a struct from a c header file as a class member to a c++ class. But I get a compiler error for the cpp file: bar was not declared inn thi

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 03:13

    Let us consider an example. Consider a Linked List in which each node is represented by:

    struct ListNode {
         int val;
         ListNode *next;
         ListNode(int x){
            val = x;
            next = NULL;
         }
    };
    

    To initialize a node with value 5 and next pointer pointing to NULL you can write the code snippet as:

    ListNode node = new ListNode();
    node.val = 5;
    node.next = NULL;
    

    or

    ListNode node = new ListNode(5);
    

    Another fancy declaration can be made as

    struct ListNode {
         int val;
         ListNode *next;
         ListNode(int x) : val(x), next(NULL) {}
    };
    

    Here ListNode(int x): val(x), next(NULL) is a constructor which initializes the value of the struct ListNode.

    Hope this make things more clear and easy. :)

提交回复
热议问题