类中的数组初始化
Array initialization in class
我尝试创建一个日期类,并希望将其中的数组设置为:
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};
相关文章:
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在函数内部的声明中初始化数组,并在外部使用它
- 为什么用结构初始化数组需要指定结构名称
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- C++使用另一个数组和新值初始化数组
- 初始化数组、"memset"或" {//value} "的最佳方法是什么?
- 在 constexpr 构造函数中初始化数组是否合法?
- 我可以初始化 const 实例,以便我可以将其用作 const 来初始化数组吗?
- 在构造函数中初始化数组
- 是否可以使用函数返回的值初始化数组
- 使用宏使用额外元素初始化数组
- 在循环中显示不同值的初始化数组
- 如何在macOS中的旧扩展clang和gcc编译器中初始化数组和向量
- 使用可变模板列表初始化数组,并放置new
- 使用函数从 Visual Studio 2017 中的 main 创建和初始化数组
- 使用 c++ 中的函数初始化数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- C++ 使用变量而不是常量表达式初始化数组
- 在初始化列表中初始化数组的更好方法
- 在可变参数模板类中初始化数组