If the class contains const static Integral Data member, the initial value can be directly given within the class according to the C ++ flag specification. The so-called integral refers to all integer types (including floating-point numbers), not just the int type. The following is an example:
#include<iostream>using namespace std;template <typename T>class testClass{public: static const double _datai=1.2; static const long _datal=3L; static const char _datac=‘c‘;};int main(){ cout<<testClass<int>::_datai<<endl; cout<<testClass<int>::_datal<<endl; cout<<testClass<int>::_datac<<endl;}
Generally, non-const static data members cannot be initialized within the class. However, we can provide static members with the class initial values of the const Integer type.
For example, the following error is reported:
#include<iostream>using namespace std;template <typename T>class testClass{public: static double _datai=1.2; static const long _datal=3L; static const char _datac=‘c‘;};int main(){ cout<<testClass<int>::_datai<<endl; cout<<testClass<int>::_datal<<endl; cout<<testClass<int>::_datac<<endl;}
Error message:
If const or constexpr is added, the class can be initialized.
For static members, if an initial value is provided inside the class, the member's definition outside the class cannot specify an initial value. For example:
#include<iostream>using namespace std;template <typename T>class testClass{public: static const double _datai=1.2; static const long _datal=3L; static const char _datac=‘c‘;};template <typename T>const double testClass<T>::_datai=8.8;int main(){ cout<<testClass<int>::_datai<<endl; cout<<testClass<int>::_datal<<endl; cout<<testClass<int>::_datac<<endl;}
Error message:
The following conditions are allowed. The initial value is provided directly at the time of definition or after the initial value is provided within the class, the initial value is only defined outside the class but not provided.
#include<iostream>using namespace std;template <typename T>class testClass{public: static const double _datai; static const long _datal=3L; static const char _datac=‘c‘;};template <typename T>const double testClass<T>::_datai=8.8;int main(){ cout<<testClass<int>::_datai<<endl; cout<<testClass<int>::_datal<<endl; cout<<testClass<int>::_datac<<endl;}
Or
#include<iostream>using namespace std;template <typename T>class testClass{public: static const double _datai=1.2; static const long _datal=3L; static const char _datac=‘c‘;};template <typename T>const double testClass<T>::_datai;int main(){ cout<<testClass<int>::_datai<<endl; cout<<testClass<int>::_datal<<endl; cout<<testClass<int>::_datac<<endl;}
STL -- Static constant integer members are directly initialized within the class