对c++结构声明中代码的目的/意义感到困惑

Confused on purpose/meaning of code in C++ struct declaration

本文关键字:结构 c++ 声明 代码      更新时间:2023-10-16

我正在尝试从头开始实现堆栈,并且我得到了工作。然而,为了编译,我需要添加几行我不知道的代码。堆栈是使用链表构建的。我为列表节点创建了如下结构体:

struct node // linked list node so store stack elements
{
    T value; // value to be store
    node *next; // pointer to next node
};

但是这不能编译。在做了一些搜索之后,我想到了这个。

struct node // linked list node so store stack elements    
{
    T value; // value to be stored
    node *next; // pointer to next node
    node(const T& newValue, node *nextNode) // ?what does this do?
        : value(newValue), next(nextNode) {} // ?what does this do?
};

我不知道为什么需要编译它,它是做什么的,并且对':'操作符特别困惑,因为我在学习c++时还没有遇到过它。

这里是所有的代码,如果它是有用的。

Stack.h

#include <iostream>
template <class T>
class Stack
{
    public:
    Stack() // constructor
    {
            t = NULL; // set bottom of stack to NULL
    }
    ~Stack() // destructor
    {
            while(!empty()) // loop to empty out stack
            {
                    pop();
            }
    }
    void push(const T& a); // add element to top of stack
    T pop(); // remove element from top of stack
    const T& top(); // return element at top of stack
    bool empty(); // check if stack is empty
    private:
    struct node // linked list node so store stack elements
    {
            T value; // value to be stored
            node *next; // pointer to next node
                    node(const T& newValue, node *nextNode) // ?what does this do?
                    : value(newValue), next(nextNode) {} // ?what does this do?
    };
    node *t; // initialize top of stack 
};
template <class T>
void Stack<T>::push(const T& a)
{
    t = new node(a, t); // set new top element, old top element pointer becomes next
}
template <class T>
T Stack<T>::pop()
{
    if(t != NULL)
    {
        node *trash = t; //hold old top node
        t = t->next; // assign new top node
        T popped = trash->value; // store old node value
        delete trash; // delete old top node
        return popped; // return old node value 
    }
}
template <class T>
const T& Stack<T>::top()
{
    if (t != NULL)
    {
        return t->value; // return top element value
    }
    else
    {
        std::cout << "StackException: Empty Stackn"; //?how can I end the program here?
    }
}
template <class T>
bool Stack<T>::empty()
{
    return t == NULL; // test to see if the stack is empty
}

您定义的成员函数(node(...))是一个构造函数,它让编译器知道当您创建类型为node的对象时该做什么。例如,在您的代码中,您在push函数中使用这个语句:t = new node(a, t);。编译器必须知道如何用传递给它的两个参数创建一个新的node

在构造函数中,需要初始化类成员。比如:
node(const T &newvalue, node *nextnode)
{
    value = newvalue;
    next = nextnode;
}

但是当编译器在node(a, t)行上使用它时,它将首先默认初始化valuenext,然后在构造函数中分配正确的值。使用构造函数初始化列表可以让编译器第一次初始化这些成员。如果T类型的对象构造成本很高,那么它可以作为提高性能的一种手段。使用构造函数初始化列表还有其他好处,你可能会在学习c++的过程中遇到它们。

构造函数后的:是成员初始化列表。它通常看起来像这样:

constructor(arguments): var1(val), var2(val) { }

您似乎也错过了template<>节点。