类中的数组初始化

Array initialization in class

本文关键字:初始化 数组      更新时间:2023-10-16

我尝试创建一个日期类,并希望将其中的数组设置为:

class Date {
private:
    int day;
    int month;
    int year;
    int daysPerMonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
};

编译器给出一个错误,禁止像这样使用数组。我该怎么做呢?

类成员的数组初始化(就地初始化,或使用初始化器列表)是c++ 11中的一个新特性。如果编译器支持更新后的语言,则可以使用以下语法:

class Date {
private:
    int daysPerMonth[12] {31,28,31,30,31,30,31,31,30,31,30,31};
};

然而,在每月天的情况下,它可能有点毫无意义(假设您只支持公历),因为这种事情倾向于被声明为static const(这些值永远不会改变,也不需要多个实例),这将允许使用c++ 11之前的语言特性轻松初始化数据。

// In the header
class Date {
private:
    static int const daysPerMonth[12];
};
// And in the implementation file
int const Date::daysPerMonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31};