简体   繁体   English

将静态常量数据成员初始化移到类定义之外

[英]Move the static constant data member initialization outside the class definition

I read that defining or initializing a static member inside the class definition would violate the idea that a class definition is only a blueprint and does not set aside any memory. 我读到,在类定义内定义或初始化静态成员会违反这样的想法,即类定义只是一个蓝图,不会保留任何内存。

But I have a constant value that I need to initialize the array inside the class, so I had to initialize it inside the class definition, and it works fine, but, is there a better method to do it? 但是我有一个常量值,需要在类内部初始化数组,因此我必须在类定义内部对其进行初始化,并且它可以正常工作,但是,有没有更好的方法呢? or this is the best method? 还是这是最好的方法?

class A{
    static const int N = 32;
    int arr[N];
};

I read that defining or initializing a static member inside the class definition would violate the idea that a class definition is only a blueprint and does not set aside any memory 我读到,在类定义内定义或初始化静态成员会违反这样的想法,即类定义只是一个蓝图,不会保留任何内存

My humble opinion: unread that thing. 我的拙见:没看过那东西。

In-class initializer is a good thing. 类内初始化器是一件好事。 Of course there are situations where is not the best solution, but in your case it's not only the best solution, it's pretty much the only solution as the size of the array must be known at compile time (except making N a template argument). 当然,在某些情况下,并不是最好的解决方案,但在您的情况下,它不仅是最好的解决方案,而且几乎是唯一的解决方案,因为必须在编译时知道数组的大小(使N为模板参数除外)。

As a side note, I would suggest you strongly consider moving away from C arrays to std::array : 作为附带说明,我建议您强烈考虑从C数组移至std::array

class A {
    static constexpr int N = 32;
    std::array<int, N> arr;
};

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

相关问题 类定义中的静态数据成员初始化? - Static data member initialization in the class definition? Class 模板 static 数据成员定义/声明/初始化 - Class template static data-member definition/declaration/initialization 在类定义之外定义私有成员函数并使用静态数据 - defining a private member function outside class definition and use of static data 在类定义中初始化静态const成员map &lt;&gt; - Initialization of static const member map<> in class definition Static 常量成员初始化在 class 之外 - Static const member initialization outside class static 成员定义外 class 模板模板 - static member definition outside class template template 在类中常量成员的初始化 - In class initialization of constant member Cpp中的私有静态数据成员只能在其定义中初始化,但是在类初始化中无效? - Private static data member in Cpp.. can only be initialized at its definition, yet invalid in-class initialization? 我应该使用类内初始化器还是在类外部定义中初始化静态const数据成员? - Should I initialize static const data member with in-class initilizer or in its definition outside class? 通过全局常量初始化静态数据成员是否会导致未定义的行为? - Does initialization of static data member by a global constant lead to undefined behavior?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM