In the implementation of member functions, non-static members described in the class cannot be directly referenced. Static members described in the class can be referenced, if a non-static member is to be referenced in a C ++ static member function, it can be referenced through an object. The following is an example to illustrate this.
- # Include
- Class M
- {
- Public:
- M (int ){A=A; B + = ;}
- Static void f1 (M m );
- Private:
- Int;
- Static int B;
- };
-
- Void M: f1 (M m)
- {
- Cout<<"A="<<
- Cout<<"B="<<
- }
-
- IntM: B=0;
- Void main ()
- {
- M p (5), Q (10 );
- M: f1 (P); file: // The object name is not used during the call.
- M: f1 (Q );
- }
You can analyze the results by yourself. It can be seen that the following format is used to call a static member function:
- <Class Name>::<Static member function name>(<Parameter table>);
Static member functions of a class cannot be called by default like non-static member functions (because static member functions do not have the implicit this parameter ). In a static member function of a class, as long as a pointer to an object of this type is obtained in some way.
With an appropriate access level, you can call non-C ++ static member functions for this object.
1. Used to save the number of objects.
- 9 phases of C ++ Compilation
- Is C ++ code in C ++ really so complicated?
- Introduction to Visual C ++ 6.0 development tools
- How to Learn C ++ library classes well?
- Analysis of C ++ function call Methods
2. As a flag, Mark whether some actions occur, such as the file opening status, printer usage status, and so on.
3. Store the memory address of the first or last member of the linked list.
Static member functions are basically equivalent to a global function with a namespace.
1. You can directly use this function without generating an object instance. For example, Cxxx: MyStaticFunc ();
2. The window callback function must use a static member function or a global function.
3. For thread calls, you must use C ++ static member functions or global functions.
Static data members can save memory because they are public to all objects. Therefore, for multiple objects, static data members can only store one object for sharing. The value of a static data member is the same for each object, but its value can be updated. You only need to update the value of the static data member once to ensure that all objects have the same value after the update, which improves the time efficiency.