search

Home  >  Q&A  >  body text

c++ - c 语言 struct 声明格式

请问一下,下面代码第五行的语法是什么意思呢?

struct ListNode {
public:
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
高洛峰高洛峰2807 days ago567

reply all(7)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:38:01

    This is C++, not C.

    reply
    0
  • 迷茫

    迷茫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.

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 14:38:01

    Isn’t this the linked list node given on LeetCode? The fifth line is the constructor.

    reply
    0
  • 迷茫

    迷茫2017-04-17 14:38:01

    It’s obvious if you understand struct as class

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:38:01

    The fifth line is the constructor in C++

    reply
    0
  • PHP中文网

    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.

    reply
    0
  • 怪我咯

    怪我咯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.

    reply
    0
  • Cancelreply