简体   繁体   English

类中的数组初始化

[英]Array initialization in class

I try to create a date class and would like to set array in it as: 我尝试创建一个日期类,并希望将数组设置为:

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

Compiler gives an error that it is forbidden to use array like this. 编译器给出一个错误,禁止使用这样的数组。 How can I do this? 我怎样才能做到这一点?

Array initialisation for class members (in-place, or with initializer lists) is a new feature in C++11. 类成员的数组初始化(就地或使用初始化列表)是C ++ 11中的一项新功能。 If you have compiler that supports the updated language, you can use the following syntax: 如果您的编译器支持更新的语言,则可以使用以下语法:

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

However, in the case of days per month it might be a little pointless (assuming you are only supporting the Gregorian calendar), because that kind of thing tends to be declared as static const (these values should never change and do not need multiple instances), which would allow the data to be initialised easily using language features that predate C++11. 但是,对于每月天数来说,这可能是没有意义的(假设您仅支持公历),因为这种事情倾向于声明为static const (这些值永远不会更改,并且不需要多个实例) ),这样可以使用C ++ 11之前的语言功能轻松地初始化数据。 eg 例如

// 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};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM