[英]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.