请问一下,下面代码第五行的语法是什么意思呢?
struct ListNode {
public:
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
迷茫2017-04-17 14:38:01
C++ structures are slightly different from C structures: C++ structures extend C structures and can have member functions. Therefore, a C++ structure is more like a class, except that all its members are public by default, which is exactly the opposite of a class.
Line 5 in the code is the constructor, followed by ":" is the parameter list of the constructor, which is used to initialize member variables.
大家讲道理2017-04-17 14:38:01
Isn’t this the linked list node given on LeetCode? The fifth line is the constructor.
PHP中文网2017-04-17 14:38:01
This is C++, the fifth line is the constructor of the class, which is initialized using the initialization list. Struct and class in C++ are similar (find the specific differences by yourself), but functions cannot be defined in struct in C language.
怪我咯2017-04-17 14:38:01
This is C++. Class definitions in C++ can be struct
or class
. The difference is that struct
members default to public
and class defaults to private
.
ListNode(int x) : val(x), next(NULL) {}
is the constructor of C++, and val(x), next(NULL)
represents initialization.