简体   繁体   English

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

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

I have a code like this: 我有这样的代码:

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

in Visual studio 2010 and I am getting this error: 在Visual Studio 2010中,我收到此错误:

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

So how to initialize a static constant float in c++? 那么如何在c ++中初始化静态常量float呢?

If I use constructor, every time that an object of this class is created, the variable is initialized which is not good. 如果我使用构造函数,每次创建此类的对象时,该变量都被初始化,这是不好的。

apparently the code is compiled with GCC on Linux. 显然代码是用Linux上的GCC编译的。

MyClass.h 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 MyClass.cpp

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

Also, concerning 另外,关心

apparently the code is compiled with GCC on Linux. 显然代码是用Linux上的GCC编译的。

This is due to an extension. 这是由于延期。 Try with flags like -std=c++98 (or -std=c++03 , or -std=c++11 if your version is recent enough) and -pedantic and you will (correctly) get an error. 尝试使用像-std=c++98 (或-std=c++03 ,或者-std=c++11如果你的版本已经足够了)这样的-pedantic并且 - 你会(正确地)得到错误。

Try the following. 请尝试以下方法。

In the header file, instead of your current statement write: 在头文件中,而不是当前的语句写:

static const float floatvalue;

In the CPP file, write: 在CPP文件中,写:

const float MyClass::floatvalue = 0.07f;

You have to define them outside of the class, as follows: 您必须在类之外定义它们,如下所示:

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

Of course, this shouldn't be done in a header, or you will get a multiple instance error. 当然,这不应该在标题中完成,否则您将获得多实例错误。 With int s, you can fake them using enum {intvalue = 50}; 使用int ,你可以使用enum {intvalue = 50};伪造它们enum {intvalue = 50}; , that won't work with floats, though. 但是,这不适用于花车。

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

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