C ++ 11:如何使用nullptr初始化某个类的指针数组?
问题描述:
我是C ++的新手.我有一个名为MyDate
的类.另外,我有一个名为Calendar
的类,该类具有指向MyDate
对象的指针数组的成员类型.我应该如何在Calendar
的构造函数中将数组的成员声明和初始化为nullptr
?
I am new to C++. I have class named MyDate
. In addition I have a class named Calendar
which has a member type of array of pointers to MyDate
objects. How should I declare and initialize members of the array to nullptr
in the constructor of Calendar
?
答
智能指针默认初始化为nullptr
:
Smart pointers default-initialize to nullptr
:
class Calendar
{
std::array<std::unique_ptr<Date>, 42> m_dates;
};
否则,std::array
是一个聚合,因此空的初始化列表将对所有标量字段进行零初始化:
Otherwise, std::array
is an aggregate, so an empty braced init list will zero-initialize all scalar fields:
class Calendar
{
std::array<Date *, 42> m_dates {};
};