When learning the idea of object-oriented programming in C++ , in the characteristics of object-oriented inheritance , in addition to the concepts of classes and objects , class constructors and destructors , and some operations on class instantiation objects , an important concept is static Member variables (static data members) and static member functions .
Questions: 1. What is a static member variable?
2. What is a static member function?
3. In-depth analysis and application
Static member variables:
1. All objects share the same data
2. Allocate memory at compile stage
3. Declare inside the class, initialize outside the class
Static member function:
1. All objects share the same function
2. Static member functions can only access static member variables
Code example:
#include<iostream> using namespace std; class Person{ public: static void show(){ m_a=10; cout<<m_a; cout<<"函数的调用"<<endl; } static int m_a; }; int Person::m_a=9;//静态数据成员类内定义类外初始化 int main() { //静态成员函数的调用方法 //通过对象访问 Person p; p.show(); //通过类名访问 Person::show(); return 0; }
Consideration case: Can the access rights of the constructor of a class be set to private? ?