简体   繁体   中英

static const double initialization in C++

I have some legacy code that I'm building with "newer" compilers and running into some static const double initialization errors that don't make sense to me. Here's what I have:

//header.h

class myclass
{
   private:
      static const double foo = 3.1415;
      static const double bar = 12345.0 * foo;
};

When compiling this code with gcc version 4.3.3 - I am seeing the following error:

 foo cannot appear in a constant-expression

I've already debunked this as not being static initialization order fiasco, as I believe intrinsic data types have a well defined order of initialization - especially when they live in the same class. As a test I've already tried to static_cast< double > the expression, but that produces yet another error stating that only integral type casts are allowed in a const expression.

static data members which are not constexpr can only be initialised directly at their declaration in the class definition if they are of integral or enumeration type. All other data types must be given a separate definition in a source file, and can only be initialised at that definition. So change your class definition to this:

class myclass
{
   private:
      static const double foo;
      static const double bar;
};

and introduce these definitions into exactly one .cpp file:

const double myclass::foo = 3.1415;
const double myclass::bar = 12345.0 * foo;

If you have access to sufficiently modern C++, you have an alternative option of changing the in-class declarations to constexpr :

class myclass
{
   private:
      static constexpr double foo = 3.1415;
      static constexpr double bar = 12345.0 * foo;
};

That way, they will not require a definition in a source file unless you use them as objects instead of as values (eg if you take their address). However, GCC 4.3.3 does not support that part of C++11.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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