c++ - c 语言 struct 声明格式
高洛峰
高洛峰 2017-04-17 14:36:01
0
7
559

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

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

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(7)
洪涛

This is C++, not C.

迷茫

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.

大家讲道理

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

迷茫

It’s obvious if you understand struct as class

Peter_Zhu

The fifth line is the constructor in C++

洪涛

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.

刘奇

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template