例如,在我声明节点struct
之后Proc
我知道它会自动将struct node {
int data;
node *next;
}
int main(){
node *root = new node;
}
初始化为0,但root->data
会发生什么。是初始化为nullptr还是什么?
答案 0 :(得分:1)
Neither of those members will be initialized as it stands. If you want them to be set to their "default values" 0
and nullptr
respectively, you can use something like this:
struct node {
int data {};
node *next {};
};
Now, in every new instance, you will have data == 0
and next == nullptr
. This C++11 feature is called "default member initializer".
If you cannot use C++11, you can achieve this value initialization either via
node* root = new node(); // <- Note the parenthesis
as @vsoftco pointed out or via aggregate initialization like this:
node root = {};
I would however prefer the variant at the top of this post if possible as it yields less opportunity for mistakes.