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;
}
Please note the comment Line1
in the sample code.
Questions:
Line1
doing the initialization of the date member data
?Line1
the only way to initialize a static const non-integral data member?Is Line1 doing the initialization of the date member data?
It certainly is, as well as providing the definition of the object. Note that this can only be done in a single translation unit, so if the class definition is in a header file, then this should be in a source file.
Is Line1 the only way to initialize a static const non-integral data member?
In C++03 it was. In C++11, any static member of const
literal type can have an initialiser in the class definition. You still need a definition of the member if it's "odr-used" (roughly speaking, if you do anything that needs its address, not just its value). In this case, the definition again needs to be in a single translation unit, and must not have an initialiser (since there's already one in the class definition).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With