[英]c++ how to assign NULL value to a member pointer when creating new struct
I'm writing a Run-length encoding project using linked list. 我正在使用链表编写一个运行长度编码项目。 Is it possible
next
to have value NULL
every time i create a Node
using new
? 每当我使用
new
创建一个Node
时,它是否可能next
有值NULL
?
I have 我有
struct Node{
int x;
char c;
Node* next;
}
and 和
class RLElist{
private:
Node* startList;
public:
/*some member functions here*/
}
I need it to be NULL
so i can check if I've reached the last Node
of the list. 我需要它为
NULL
所以我可以检查我是否已到达列表的最后一个Node
。
Yes. 是。 And as usual with something that is possible, in this case too there is more than single way to do it.
和往常一样,在这种情况下,也可以采用单一方式。
If you call a new
operator with value initilization semantics 如果使用值初始化语义调用
new
运算符
Node* n = new Node();
than value initialization will be triggered and this will assign 0 value to each structure's data member if there is no user defined constructor in the structure. 比值初始化将被触发,如果结构中没有用户定义的构造函数,这将为每个结构的数据成员分配0值。
You can also define a default constructor that will assign null to pointer ( and maybe do something else as well) 您还可以定义一个默认构造函数,它将为指针指定null(也可能执行其他操作)
struct Node{
int x;
char c;
Node* next;
Node() : next( 0) {}
}
and use this as before 并像以前一样使用它
Node* n = new Node(); // your constructor will be called
And finally, you can initialize pointer in the place of it's declaration 最后,您可以在声明的位置初始化指针
struct Node{
int x;
char c;
Node* next = nullptr;
};
There are different options: 有不同的选择:
Add a constructor that value-initializes the pointer (which leaves it zero-initialized): 添加一个构造函数,用于初始化指针(使其初始化为零):
struct Node{
Node() : next() {} // you can also value initialize x and c if required.
int x;
char c;
Node* next;
};
Initialize at the point of declaration: 在声明点初始化:
struct Node{
int x;
char c;
Node* next = nullptr;
};
Value-initialize the new
ed object: 值初始化
new
ed对象:
node* Node = new Node(); // or new Node{};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.