我正在使用链表编写一个运行长度编码项目。每次使用next
创建NULL
时,Node
是否有值new
?
我有
struct Node{
int x;
char c;
Node* next;
}
和
class RLElist{
private:
Node* startList;
public:
/*some member functions here*/
}
我需要它NULL
所以我可以检查我是否已到达列表的最后Node
。
答案 0 :(得分:5)
是。和往常一样,在这种情况下,只有一种方法可以做到这一点。
如果您使用value initilization语义调用new
运算符
Node* n = new Node();
将触发值初始化,如果结构中没有用户定义的构造函数,这将为每个结构的数据成员分配0值。
您还可以定义一个默认构造函数,它将null赋给指针(也可能做其他事情)
struct Node{
int x;
char c;
Node* next;
Node() : next( 0) {}
}
并像以前一样使用
Node* n = new Node(); // your constructor will be called
最后,您可以在声明的位置初始化指针
struct Node{
int x;
char c;
Node* next = nullptr;
};
答案 1 :(得分:5)
有不同的选择:
添加一个构造函数,对指针进行值初始化(使其保持零初始化):
struct Node{
Node() : next() {} // you can also value initialize x and c if required.
int x;
char c;
Node* next;
};
在声明点初始化:
struct Node{
int x;
char c;
Node* next = nullptr;
};
值初始化new
ed对象:
node* Node = new Node(); // or new Node{};