c++ - Why can't I have a non-integral static const member in a class? -
i noticed c++ not compile following:
class no_good { static double const d = 1.0; };
however happily allow variation double changed int, unsigned, or integral type:
class happy_times { static unsigned const u = 1; };
my solution alter read:
class now_good { static double d() { return 1.0; } };
and figure compiler smart enough inline necessary... left me curious.
why c++ designer(s) allow me static const int or unsigned, not double?
edit: using visual studio 7.1 (.net 2003) on windows xp.
edit2:
question has been answered, completion, error seeing:
error c2864: 'd' : const static integral data members can initialized inside class or struct
the problem integer, compiler usually doesn't have ever create memory address constant. doesn't exist @ runtime, , every use of gets inlined surrounding code. can still decide give memory location - if address ever taken (or if it's passed const reference function), must. in order give address, needs defined in translation unit. , in case, need separate declaration definition, since otherwise defined in multiple translation units.
using g++ no optimization (-o0
), automatically inlines constant integer variables not constant double values. @ higher optimization levels (e.g. -o1
), inlines constant doubles. thus, following code compiles @ -o1
not @ -o0
:
// file a.h class x { public: static const double d = 1.0; }; void foo(void); // file a.cc #include <stdio.h> #include "a.h" int main(void) { foo(); printf("%g\n", x::d); return 0; } // file b.cc #include <stdio.h> #include "a.h" void foo(void) { printf("foo: %g\n", x::d); }
command line:
g++ a.cc b.cc -o0 -o # linker error: ld: undefined symbols: x::d g++ a.cc b.cc -o1 -o # succeeds
for maximal portability, should declare constants in header files , define them once in source file. no optimization, not hurt performance, since you're not optimizing anyways, optimizations enabled, can hurt performance, since compiler can no longer inline constants other source files, unless enable "whole program optimization".
Comments
Post a Comment