For the C ++ object model, the static member variables are involved in the previous reading note. Later, I found that there are still many things to think about, and I will explain them one by one.
First, static member in the class is not included in the computing class size. For example, why?
(X) =;View Code
Most people should know that static member is equivalent to a global variable, and global variables are stored in a static zone, so they are separated from classes or objects. Therefore, sizeof (X) is calculated) is not included. Since static member is a global variable, no matter how many objects are generated in the program, static member will always have only one instance. Even if the class does not have any instances, its static member can already exist.
Second, it is not enough to declare the static members of the struct class. The above class X only declares the num. If you instantiate an object directly in other functions, use this object to access static member num, then the compiler will give you an external command similar to "fatal error LNK1120: 1 unresolvable. Why? Because the static int num in the class is just a declaration, not a definition! To access a variable, it must be defined! The definition must be outside the class (and cannot be inside other functions, just like defining global variables ). Here, we can directly define int X: num = 10 outside class X, and then we can directly access it.
When it comes to the use of static member variables, we can't help but think of the implementation of the singleton mode. The following briefly introduces the singleton mode.
Singleton may be the most widely used design pattern to ensure that only one object of this type can be instantiated for a class and a global access point can be provided. In many cases, you can compare the singleton mode. For example, a system should only have one file system and one window manager, and a program can only generate one interactive window. A common implementation method is to hide the operation for creating this unique instance in a class operation, which ensures that only one instance is created. This operation can save the variables of a unique instance and ensure that the instance is created when no instance is created. Below is an implementation:
Singleton * setVar (~ Singleton * Singleton: m_instance =-> = cout <Singleton ::~ Cout <Singleton * (m_instance =-> Singleton: setVar (->=}View Code
You can test the getVar () and setVar () operations in the main function to check whether the operation is performed on the same instance.