结构成员的默认值
Default value of a struct member
(我确定这个问题已经得到回答,我只是不确定用正确的词来问它。如果有人能告诉我正确的术语是什么真棒!)
我正在用 C++ 为数据结构 class 实现 HashSet
,我对结构的 C++ 语法有疑问。这是我的代码:
struct HashNode
{
T value;
HashNode* next = nullptr;
};
当调用 new HashNode
时,此代码能否正确地将 next
指针初始化为 nullptr
?如果不是,new HashNode
之后的next
的值是多少?
Will this code correctly initialize the next pointer to nullptr when new HashNode is called?
是的,它将被初始化为nullptr
。这是 in-class brace-or-equal initializer (default member initializer) (C++11 起),如果在成员初始值设定项列表中省略成员,将使用它。
Through a default member initializer, which is simply a brace or
equals initializer included in the member declaration, which is used
if the member is omitted in the member initializer list
If a member has a default member initializer and also appears in the
member initialization list in a constructor, the default member
initializer is ignored.
(我确定这个问题已经得到回答,我只是不确定用正确的词来问它。如果有人能告诉我正确的术语是什么真棒!)
我正在用 C++ 为数据结构 class 实现 HashSet
,我对结构的 C++ 语法有疑问。这是我的代码:
struct HashNode
{
T value;
HashNode* next = nullptr;
};
当调用 new HashNode
时,此代码能否正确地将 next
指针初始化为 nullptr
?如果不是,new HashNode
之后的next
的值是多少?
Will this code correctly initialize the next pointer to nullptr when new HashNode is called?
是的,它将被初始化为nullptr
。这是 in-class brace-or-equal initializer (default member initializer) (C++11 起),如果在成员初始值设定项列表中省略成员,将使用它。
Through a default member initializer, which is simply a brace or equals initializer included in the member declaration, which is used if the member is omitted in the member initializer list
If a member has a default member initializer and also appears in the member initialization list in a constructor, the default member initializer is ignored.