繁体   English   中英

如何在Visual Studio中初始化C ++类中的静态const浮点数

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

我有这样的代码:

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 ++中初始化静态常量float呢?

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

显然代码是用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};伪造它们enum {intvalue = 50}; 但是,这不适用于花车。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM