对c++结构声明中代码的目的/意义感到困惑
Confused on purpose/meaning of code in C++ struct declaration
我正在尝试从头开始实现堆栈,并且我得到了工作。然而,为了编译,我需要添加几行我不知道的代码。堆栈是使用链表构建的。我为列表节点创建了如下结构体:
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)
行上使用它时,它将首先默认初始化value
和next
,然后在构造函数中分配正确的值。使用构造函数初始化列表可以让编译器第一次初始化这些成员。如果T
类型的对象构造成本很高,那么它可以作为提高性能的一种手段。使用构造函数初始化列表还有其他好处,你可能会在学习c++的过程中遇到它们。
构造函数后的:
是成员初始化列表。它通常看起来像这样:
constructor(arguments): var1(val), var2(val) { }
您似乎也错过了template<>
节点。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++概念:如何使用'concept'检查模板化结构的属性?