Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我读到在类定义中定义或初始化静态成员会违反类定义只是一个蓝图并且不留出任何内存的想法。
但是我有一个常量值,我需要在类中初始化数组,所以我必须在类定义中初始化它,它工作正常,但是,有更好的方法吗?或者这是最好的方法?
class A{ static const int N = 32; int arr[N]; };
我读到在类定义中定义或初始化静态成员会违反类定义只是一个蓝图并且不留出任何内存的想法
我的拙见:未读那件事。
类内初始化器是一件好事。当然,有些情况不是最好的解决方案,但在您的情况下,它不仅是最好的解决方案,而且几乎是唯一的解决方案,因为在编译时必须知道数组的大小(除了制作N模板参数)。
N
作为旁注,我建议您强烈考虑从 C 数组移到std::array:
std::array
class A { static constexpr int N = 32; std::array<int, N> arr; };