C++单例类中如何基于编译期float常量定义固定尺寸静态数组
问题原因
普通类内const成员不属于编译期可求值的常量表达式,C++标准要求栈数组的长度必须是编译期确定的常量,因此你当前的写法无法通过编译。你定义的const float和const int都是实例级成员,理论上可以在构造函数初始化列表中覆盖默认值,编译器无法在编译阶段确定sz_arr的全局固定值。
解决方案
方案1:使用constexpr修饰(推荐,C++11及以上版本支持)
用constexpr关键字标记编译期常量,修饰的变量会在编译阶段完成求值,完全符合你的需求:
class myclass : public singleton<myclass> { public: myclass(); private: static constexpr float myfloat = 6000.0f; static constexpr int sz_arr = static_cast<int>(myfloat); int arr[sz_arr]; // 编译正常 };
说明:
constexpr默认隐含静态属性,属于类本身而非实例,值在编译期固定- 后续调整数组大小时仅需修改
myfloat的取值即可,sz_arr会自动完成编译期计算 - 作为单例类不会产生多实例的内存冗余,完全满足你的使用场景
方案2:用枚举常量实现(兼容旧标准C++版本)
如果你的编译环境不支持C++11,可以用枚举值作为编译期常量实现:
class myclass : public singleton<myclass> { public: myclass(); private: enum { sz_arr = static_cast<int>(6000.0f) }; int arr[sz_arr]; // 编译正常 // 若需要单独保留myfloat常量,可以额外定义const float myfloat = 6000.0f; };
枚举值本质是编译期整数常量,可以直接用来指定数组长度。
内容的提问来源于stack exchange,提问作者user3600124
相关产品推荐
相关产品推荐

