Detailed explanation of static member static

When I was interviewing for the C++ position of NIO yesterday, I inevitably asked about the static keyword. However, I only knew a little about it before, so I was stuck with this question, so I simply figured out this question thoroughly today. ~

About static members

  • static data members
  • static function member
  • static const member

static data members

  • Objects are instances of classes, and data members declared in a class have a copy in every object of that class. Sometimes objects of a class may need to share some information. For example, in a banking system, the most important objects are individual accounts, for which an account class needs to be defined. Each account contains information such as account number, deposit date, deposit amount, etc. In order to calculate interest on an account, you also need to know the interest rate. The interest rate is information that every account object must know, and this value is the same for all account class objects. Therefore, there is no need to set such a data member for each object, just let all objects share such a value.
  • Shared information is generally represented by global variables, but if the shared data is represented by global variables, there is a lack of data protection. Because global variables are not limited by the access control of the class, in addition to objects of the class can access it, objects of other classes and global functions can often read these global variables. It is also easy to conflict with other names.
  • It would be ideal if a piece of data could be stored as a global variable, but hidden in a class, and clearly express the connection with the class.

This functionality can be achieved through static data members. Static data members of a class have a separate storage area, regardless of how many objects of that class are created. All static data members of these objects share this space. But static data members belong to the class, its name is only valid within the scope of the class, and can be public or private, which in turn protects him from interference from other global functions.

To declare some data members as static, just add the keyword static before the data members

Definition of Bank Account Class

class SavingAccount {
    
    
private:
	char AccountNumber[20];   // 账号
	char SavingDate[8];  // 存款日期,格式为YYYYMMDD
	double balance;     // 存款额
	static double rate;  // 利率,为静态数据成员(类内声明)
}

double SavingAccount::rate = 0.5; // 类外初始化

The class definition just gives a description of the object structure, and the real storage space is allocated when the object is defined. However, since static data members belong to classes rather than objects, the system does not include the space for static data members when allocating space for objects. Therefore, the space for static data members must be allocated separately, and must be allocated only once. Allocating space for a static data member becomes the initialization (definition) of the static data member. The initialization of static data members generally appears in the implementation file of the class.

Static data members belong to the class, so you can pass scope::static data member name. But from the perspective of each object, it seems to be part of the object, so it can be referenced by the object like a normal member. But no matter which object, it refers to the same space.

static member function

  • Like static data members, member functions can also be static.
  • Static member functions are used to manipulate static data members, which serve classes rather than objects of classes.
  • The operations performed by static member functions will affect all objects of the class, not a specific object. Putting such a function inside the class eliminates the need to define a global function, which reduces the footprint of the global namespace.

The declaration of a static member function only needs to add the keyword static before the function prototype in the class definition.
Like ordinary member functions, the definition of static member functions can be written in the class definition or outside the class definition .
When defined outside the class, there is no need to add static to the function definition.

  • Static member functions can be called with objects. However, the more typical method is to call it by class name, which is of the form "class name::static member function name()"
  • Static member functions serve classes, and its biggest feature is that there is no this pointer. Therefore, static member functions cannot access general data members, but can only access static data members or other static member functions.
  • The main purpose of defining a static member function is to access static data members . Because it does not belong to any object, it can be used to process static data members before any object is created, such as initializing the value of static data members. This is a function that ordinary member functions cannot achieve.

Definition of StaticSample class

// 文件名:StaticSample.h
// 静态数据成员和静态成员函数示例
#ifndef _StaticSample_h
#define _StaticSample_h
#include <iostream>
using namespace std;

class StaticSample {
    
    
private:
	static int obj_count;  // 静态数据成员
	static int obj_living;
public:
	StaticSample() {
    
    
		++obj_count;
		++obj_living;
	}
	~StaticSample() {
    
    
		--obj_living;
	}
	static void display() {
    
    
		cout << "总对象数:" << obj_count << "\t存活对象数:" << obj_living << endl;
	}  // 静态成员函数的类内实现
};
#endif // !1
// StaticSample.cpp
#include "StaticSample.h"
int StaticSample::obj_count = 0;
int StaticSample::obj_living = 0;

Use of the StaticSample class

// 文件名:Static_Sample.cpp
// Static Sample类的使用
#include "StaticSample.h"

int main() {
    
    
	StaticSample::display();  // 通过类名限定调用静态成员函数

	StaticSample s1, s2;
	StaticSample::display();

	StaticSample* p1 = new StaticSample, * p2 = new StaticSample;
	s1.display();  // 通过对象调用静态成员函数

	delete p1;
	p2->display();  // 通过指向对象的指针来调用静态成员函数

	delete p2;
	StaticSample::display();

	return 0;
}

The result of running the program

Picture 1

static const member

  • Static data members are data members shared by the entire class. Sometimes all objects of the entire class need to share a constant, and this member can be set as a static constant member. Static constant data members are declared with the keyword static const.
  • Note the difference between constant data members and static constant data members. Constant data members belong to each object, and the values ​​of constant data members of different objects are different. Static constant data members belong to the entire class, and the static constant data members of different objects are the same.
  • In general, data members of a class cannot be initialized at class definition time. Ordinary data members are initialized by the constructor when the object is defined. Static data members are initialized when the static data member is defined. There is only one exception to this rule, and that is for static constant data members. Static const data members can and must be initialized at class definition time.

Guess you like

Origin blog.csdn.net/loveCC_orange/article/details/125904995