如何在Visual Studio中初始化C++类中的静态常量浮点值

How to initialize a static const float in a C++ class in Visual Studio

本文关键字:静态 常量 C++ Visual Studio 初始化      更新时间:2023-10-16

我有一个这样的代码:

class MyClass
{
   private:
     static const int intvalue= 50;
     static const float floatvalue = 0.07f;
 };

在Visual studio 2010中,我得到了这个错误:

Myclasses.h(86): error C2864: 'MyClass::floatvalue : only static const integral data members can be initialized within a class

那么,如何在c++中初始化静态常量浮点呢?

如果我使用构造函数,那么每次创建此类的对象时,都会初始化变量,这是不好的。

显然,代码是在Linux上使用GCC编译的。

MyClass.h

class MyClass
{
   private:
     static const int intvalue = 50; // can provide a value here (integral constant)
     static const float floatvalue; // canNOT provide a value here (not integral)
};

MyClass.cpp

const int MyClass::intvalue; // no value (already provided in header)
const float MyClass::floatvalue = 0.07f; // value provided HERE

此外,关于

显然,代码是在Linux上使用GCC编译的。

这是由于延期。尝试使用-std=c++98(或-std=c++03,或-std=c++11,如果您的版本足够新)和-pedantic等标志,您将(正确地)得到错误。

尝试以下操作。

在头文件中,代替您当前的语句写:

static const float floatvalue;

在CPP文件中,写入:

const float MyClass::floatvalue = 0.07f;

您必须在类之外定义它们,如下所示:

const int MyClass::intvalue = 50;
const float MyClass::floatvalue = 0.07f;

当然,这不应该在头中完成,否则会出现多实例错误。对于int,您可以使用enum {intvalue = 50};来伪造它们,但这在浮点运算中不起作用。