Initialize a static constant data element that is not an integral of the class

Consider the sample program below:

#include <iostream> using namespace std; class test { public: static const float data; }; float const test::data = 10; // Line1 int main() { cout << test::data; cout << "\n"; return 0; } 

Notice the Line1 comment in the sample code.

Questions:

  • Are you initializing the data element data Line1 ?
  • Is Line1 only way to initialize a data item that is not an integral constant?
+7
source share
5 answers

Is Line1 initializing date member data?

This, of course, is the same as the definition of the definition of an object. Note that this can only be done in one translation unit, so if the class definition is in the header file, then it must be in the source file.

Is Line1 the only way to initialize a data item that is not an integral constant?

In C ++ 03 it was. In C ++ 11, any static member of type const literal can have an initializer in the class definition. You still need a member definition if it is "used by odr" (roughly speaking, if you are doing something that requires its address, not just its value). In this case, the definition should again be in one translation unit and should not have an initializer (since the class definition is no longer in place).

+7
source
  • Line1 defines the definition of the static data member data , which includes setting its value.
  • For non-integer static data elements, member definition is really the only place to set the value. For integers, longs, enumerations, etc. You can put a value in an ad. You should still include a definition, but in this case you should not specify any value.

EDIT: As Mike Seymour noted, number 2 is out of date. According to the new C ++ 11 standard, an alternative syntax that was reserved only for integral types according to the 1998 and C ++ 03 standards was extended to all constants regardless of their type.

+4
source

In modern C ++, you can initialize any constant inline expression. This requires a change of syntax:

 class test { public: static constexpr float data = 10.0f; }; float constexpr test::data; 
+4
source
  • Yes.

2.

In C ++ 11 you can say

 class test { public: constexpr static float data = 10.0; // data is implicitly const }; 

In C ++ 03, it is.

+2
source

Is Line1 initializing date member data?

Yes.

Is Line1 the only way to initialize static constant nonintegral data as a member?

Yes.

0
source

All Articles