Static member variable
Static member variable is similar to global variable , but it is applied to class.
Static member variables only exist once in a program regardless of how many class objects are defined!
One way to think about it is that all objects of a class share the static variables.
(The static member variable is defined in private area in this situation.)
for example :
class Something{private: static int s_nIDGenerator; int m_nID;public: Something() { m_nID = s_nIDGenerator++; } int GetID() const { return m_nID; }};int Something::s_nIDGenerator = 1;int main(){ Something cFirst; Something cSecond; Something cThird; using namespace std; cout << cFirst.GetID() << endl; cout << cSecond.GetID() << endl; cout << cThird.GetID() << endl; return 0;}
We can also define the static member variable in the public area ,
it means that the variable exists independently ,
it can be accessed directly using the class name and the scope operator.
for example :
class Something{public: static int s_nValue;};int Something::s_nValue = 1;int main(){ Something cFirst; cFirst.s_nValue = 2; Something cSecond; std::cout << cSecond.s_nValue; return 0;}
文章標籤
全站熱搜
