#include<iostream>classSomething{private:staticints_value;public:staticintgetValue(){returns_value;}// static member function};intSomething::s_value{1};// initializerintmain(){std::cout<<Something::getValue()<<'\n';}
#include<iostream>classIDGenerator{private:staticints_nextID;// 静态成员的声明public:staticintgetNextID();// 静态函数的声明};// 在类外定义静态成员。注意,我们在此处没有使用 static 关键字。// ID 从 1 开始intIDGenerator::s_nextID{1};// 类外定义静态成员函数。注意,我们在此处没有使用 static 关键字。intIDGenerator::getNextID(){returns_nextID++;}intmain(){for(intcount{0};count<5;++count)std::cout<<"The next ID is: "<<IDGenerator::getNextID()<<'\n';return0;}
打印结果:
12345
The next ID is: 1
The next ID is: 2
The next ID is: 3
The next ID is: 4
The next ID is: 5
classMyClass{public:staticstd::vector<char>s_mychars;};std::vector<char>MyClass::s_mychars{[]{// The parameter list of lambdas without parameters can be omitted.// Inside the lambda we can declare another vector and use a loop.std::vector<char>v{};for(charch{'a'};ch<='z';++ch){v.push_back(ch);}returnv;}()// Call the lambda right away};
classMyClass{public:staticstd::vector<char>s_mychars;classinit_static// we're defining a nested class named init_static{public:init_static()// the init constructor will initialize our static variable{for(charch{'a'};ch<='z';++ch){s_mychars.push_back(ch);}}};private:staticinit_statics_initializer;// we'll use this static object to ensure the init_static constructor is called};std::vector<char>MyClass::s_mychars{};// define our static member variableMyClass::init_staticMyClass::s_initializer{};// define our static initializer, which will call the init_static constructor, which will initialize s_mychars