C++ static member variables

Static member variable

1. Add the keyword static before member variables and member functions, which are called static members.
2. Static member variables: All objects share a piece of data, allocate memory during compilation, declare within the class, and initialize outside the class.

class Person
{
    
    
public:
	static int m_A;
private:
	static int m_B;
};
int Person::m_A = 100;
int Person::m_B = 100;

The appeal is the definition of the class Person, the following code is used as a test

Person p1;
	p1.m_A = 150;
	cout << "p1中的m_A为:" << p1.m_A << endl;//通过对象访问静态成员变量

	Person p2;
	p2.m_A = 200;
	cout << "p1的m_A成员变量为:" << p1.m_A << endl;
	cout << "p2的m_A成员变量为:" << p2.m_A << endl;

	p1.m_A = 300;
	cout << "p1和p2的m_A成员变量为:" << Person::m_A << endl;//通过类名访问静态成员变量

The test results are as follows:

p1中的m_A为:150
p1的m_A成员变量为:200
p2的m_A成员变量为:200
p1和p2的m_A成员变量为:300
请按任意键继续. . .

3. Two ways to access static member variables:
(1). Access static member variables through objects;
(2) Access static member variables through class names;
4. Static member functions:
(1) All objects share the same function ;
(2), static member functions can only access static member variables

class Person
{
    
    
public:
	static int m_A;
	int m_B;

	static void func1()
	{
    
    
		m_A = 150;
		//m_B = 200;  非静态成员变量不可访问
		cout << "Person中的m_A为:"<<Person::m_A << endl;
	}

private:
	static void func2()
	{
    
    
		cout << "静态成员函数func2()的调用" << endl;
	}
};
int Person::m_A = 10;

It can be seen from the appeal code that static member variables are declared within the class and initialized outside the class. The static member function func1 can only access static member variables, not non-static member variables.
Down the code as a test

//1、通过对象访问
	Person p1;
	p1.func1();

	//2、通过类名访问
	Person::func1();

The output test is as follows:

Person中的m_A为:150
Person中的m_A为:150
请按任意键继续. . .

Guess you like

Origin blog.csdn.net/Little_XWB/article/details/108184208