链表C++的语法

Syntax for linked list C++

本文关键字:语法 C++ 链表      更新时间:2023-10-16

我正在为我的C++类制作一个链表,我正在查看教授的一些代码:

void List::add(char c)
{
    Node    *newNode(new Node(c));
    if (last == nullptr)
        first = last = newNode;
    else {
        last->next = newNode;
        last = newNode;
        }
}
int List::find(char c)
{
    Node    *node(first);
    int     i(0);
    while (node) {
        if (node->c == c)
            return i;
        node = node->next;
        i++;
        }
    return -1;

以下是头文件中的类声明:

class List
{
public:
    List(void);
    ~List(void);
    void add(char c);
    int find(char c);
    bool remove(int index);
    int length(void);
    friend std::ostream& operator<<(std::ostream& out, List& list);
private:
    class Node
    {
    public:
        Node(char c) : c(c), next(nullptr) { }
        char    c;
        Node    *next;
    };
    Node    *first;
    Node    *last;
};

第一个问题:括号是什么意思?正确的使用方法是什么?

Node    *newNode(new Node(c));
Node    *node(first);
int     i(0);

第二个问题:以下是什么意思?

Node(char c) : c(c), next(nullptr) { }

我过去曾使用结构定义过一个节点;语法不同是因为这是一个类吗?

此语句

Node    *newNode(new Node(c));
Node    *node(first);
int     i(0);

相当于

Node    *newNode = new Node(c);
Node    *node = first;
int     i = 0;

Node 类的这个构造函数

Node(char c) : c(c), next(nullptr) { }

使用mem初始值设定项列表: c(c), next(nullptr)来初始化类的数据成员。即数据成员c由构造函数参数c初始化,而数据成员next由指针文字nullptr

初始化