我正在尝试从头开始实现一个堆栈,我让事情有效。但是,要编译的东西,我需要添加几行代码,我不知道。堆栈使用链表构建。我为列表节点创建了一个结构,如下所示:
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 ++时遇到它。
以下是所有代码,以防它有用。
#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 Stack\n"; //?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
}
答案 0 :(得分:2)
您定义的成员函数(node(...)
)是一个构造函数,让编译器知道在node
类型上创建对象时要执行的操作。例如,在您的代码中,您在push
函数中使用此语句:t = new node(a, t);
。编译器必须知道如何使用传递给它的两个参数创建新的node
。
在构造函数中,您需要初始化类成员。类似的东西:
node(const T &newvalue, node *nextnode)
{
value = newvalue;
next = nextnode;
}
但是当编译器在行node(a, t)
上使用它时,它将首先默认初始化value
和next
,然后在构造函数中分配正确的值。使用构造函数初始化列表可让编译器第一次初始化这些成员。如果T
类型的对象构造起来很昂贵,它可以是一种提高性能的方法。使用构造函数初始化列表可以获得其他好处,当您了解有关C ++的更多信息时,您可能会遇到它们。
答案 1 :(得分:0)
构造函数之后的:
是member initializer list。它通常看起来像这样:
constructor(arguments): var1(val), var2(val) { }
您似乎也错过了节点上的template<>
。