gpt4 book ai didi

c++ - 声明浮点常量时出错

转载 作者:行者123 更新时间:2023-11-28 03:41:22 25 4
gpt4 key购买 nike

我正在声明一个需要一些公共(public)常量的类。我的想法是像这样声明:

class MyClass {
public:
const int kIntConst = 1234;
const float kFloatConst = 1234.567f;
// ...methods...
};

此方法对 int 常量有效,但对 float 常量无效,并出现以下错误:

error C2864: 'MyClass::kFloatConst' : only static const integral data members can be initialized within a class

好吧,我确实理解这个错误信息。它说我不能在类声明中声明 float (非整数)常量。所以,问题是:为什么!?为什么它可以是int而不是float

我知道如何解决这个问题。将 kFloatConst 声明为静态 const 成员,然后在 .cpp 中进行初始化可以解决问题,但这不是我想要的。我需要一个编译时常量(一个可以被编译器优化的常量),而不是一个需要 .obj 文件链接的常量类成员。

使用宏可能是一种选择,但宏没有命名空间,而且我不喜欢全局定义的常量。

最佳答案

一般规则是您不能在类声明中定义常量。

然后有一个异常(exception),即整数常量无论如何都是允许的。所以 int 常量不是规则,而是异常(exception)。

关于c++ - 声明浮点常量时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9138979/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com