当前位置:网站首页>Static details of static members
Static details of static members
2022-07-28 22:26:00 【loveCC_ orange】
Wei Lai was interviewed yesterday C++ When you're in a position , Inevitably asked static Keyword things , However, I only knew a little before , Only know about , So I got stuck by this problem , So today, I simply make this problem clear ~
About static members
- Static data members
- Static function members
- Static constant members
Static data members
- Object is an instance of a class , The data members described in the class have a copy in each object of the class . Sometimes , Class objects may need to share some information . for example , In a banking system , The main objects are accounts , To do this, you need to define an account class . Each account contains information such as account number 、 Deposit date 、 Deposit amount, etc . In order to calculate the interest of the account , You also need to know the interest rate . Interest rate is the information that every account object must know , And for all account class objects , This value is the same . Therefore, it is not necessary 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 you use global variables to represent this shared data , Lack of data protection . Because global variables are not limited by the access control of the class , Except that 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 .
- If you can store a data as a global variable , But it is hidden in the class , And clearly indicate the connection with this class , That's the ideal .
This function can be realized through static data members . The static data members of the class have a separate storage area , No matter how many objects of this class are created . Static data members of all these objects share this space . But static data members belong to classes , Its name is valid only within the scope of the class , And it can be public or private , This in turn keeps him from being disturbed by other global functions .
Some data members should be described as static , Just add keywords before this data member static
Definition of bank account class
class SavingAccount {
private:
char AccountNumber[20]; // account number
char SavingDate[8]; // Date of deposit , The format is YYYYMMDD
double balance; // Deposit amount
static double rate; // The interest rate , Is a static data member ( Declaration within class )
};
double SavingAccount::rate = 0.5; // Class initialization
Class definition only gives the description of object composition , The real storage space is allocated when the object is defined . But because static data members belong to classes rather than objects , Therefore, when the system allocates space for objects , Space that does not include static data members . therefore , The space of static data members must be allocated separately , And it must be allocated only once . Allocate space for static data members to become initialization of static data members ( Definition ). Initialization of static data members usually occurs in the implementation file of classes .
Static data members belong to classes , Therefore, the scope :: Static data member name . But from the perspective of each object , It seems to be part of the object again , Therefore, it can be referenced by objects like ordinary members . But no matter which object , All references are the same space .
Static member functions
- Like static data members , Member functions can also be static .
- Static member functions are used to manipulate static data members , It serves classes, not class objects .
- The operations of static member functions will affect all objects of the class , Not a specific object . Put such a function inside the class , There is no need to define a global function , Reduce the occupation of global namespace .
The declaration of static member functions only needs to add keywords before the function prototype in the class definition static.
It is the same as ordinary member functions , The definition of static member function can Written in the class definition , It's fine too Write it outside the class definition .
When defined outside the class , There is no need to add... In the function definition static.
- Static member functions can be called with objects . However , A more typical method is to call... By class name , namely “ Class name :: Static member function name ()” In the form of
- Static member functions serve classes , Its biggest feature is that there is no this The pointer , therefore , Static member functions cannot access general data members , You can only access static data members or other static member functions .
- The main purpose of defining static member functions is to access static data members . Because it does not belong to any object , therefore , You can use it 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 .
StaticSample The definition of a class
// file name :StaticSample.h
// Examples of static data members and static member functions
#ifndef _StaticSample_h
#define _StaticSample_h
#include <iostream>
using namespace std;
class StaticSample {
private:
static int obj_count; // Static data members
static int obj_living;
public:
StaticSample() {
++obj_count;
++obj_living;
}
~StaticSample() {
--obj_living;
}
static void display() {
cout << " Total number of objects :" << obj_count << "\t Number of surviving objects :" << obj_living << endl;
} // In class implementation of static member functions
};
#endif // !1
// StaticSample.cpp
#include "StaticSample.h"
int StaticSample::obj_count = 0;
int StaticSample::obj_living = 0;
StaticSample The use of the class
// file name :Static_Sample.cpp
// Static Sample The use of the class
#include "StaticSample.h"
int main() {
StaticSample::display(); // Call static member functions through class name qualification
StaticSample s1, s2;
StaticSample::display();
StaticSample* p1 = new StaticSample, * p2 = new StaticSample;
s1.display(); // Call static member functions through objects
delete p1;
p2->display(); // Call a static member function by pointing to an object
delete p2;
StaticSample::display();
return 0;
}
The running result of the program
Static constant members
- Static data members are data members shared by the entire class . Sometimes all objects of the entire class need to share a constant , At this point, you can set this member as a static constant member . Static constant data members use keywords static const Statement .
- Be careful , The difference between constant data members and static constant data members . Constant data members belong to various objects , The values of constant data members of different objects are different . Static constant data members belong to the whole class , The static constant data members of different objects are the same .
- generally speaking , Data members of a class cannot be initialized when the class is defined . Ordinary data members are defined in the object , They are initialized by the constructor . Static data members are initialized when static data members are defined . There is only one exception to this rule , For static constant data members . Static constant data members can and must be initialized at class definition .
边栏推荐
- CDN working principle
- SQL注入 Less34(POST型宽字节注入+布尔盲注)
- Alibaba cloud CDN practice
- HYDAC overflow valve db08a-01-c-n-500v
- [CS231N]Lecture_ 2:Image Classification pipelin
- SQL injection less38 (Stack Injection)
- HCIP(13)
- Sword finger offer II 055. Binary search tree iterator (medium binary search tree iterator)
- Sword finger offer II 054. Sum of all values greater than or equal to nodes (medium binary search tree DFS)
- 2021年数学建模B组代码
猜你喜欢
C语言编程规范学习笔记和总结
Which is the file transfer command in the basic services of the Internet
[LiteratureReview]Object Detection and Mapping with Bounding Box Constraints
MySQL built-in functions
Desai wisdom number - line chart (stacking area chart): ranking of deposits of different occupational groups in the proportion of monthly income in 2022
Sword finger offer II 052. flatten binary search tree (simple binary search tree DFS)
internet的基本服务中文件传输命令是哪个
LVS+KeepAlived高可用部署实战应用
hcip实验(15)
Sword finger offer II 054. Sum of all values greater than or equal to nodes (medium binary search tree DFS)
随机推荐
Ruiji takeout - background login function development
HCIP(13)
SQL injection less34 (post wide byte injection + Boolean blind injection)
科大讯飞笔试
HCIP第七次实验
Chapter 7: drawing rotating cubes
Sword finger offer II 056. Sum of two nodes in a binary search tree (simple binary search tree DFS hash table double pointer iterator)
HCIP(12)
DHCP和PPPoE协议以及抓包分析
Bugku,Web:都过滤了
The difference between get and post
Learn kotlin - extension function
Openresty request authentication
[leetcode] maximum depth of binary tree
What is time complexity
Sword finger offer II 057. the difference between the value and the subscript is within the given range (medium array bucket sort sliding window TreeSet)
Lin Xiaobin, head of Tencent cloud database, borrowed 100 million yuan to speculate in stocks? Insider: the amount is not true
mysql create语句能不能用来建立表结构并追加新的记录
【机器学习】朴素贝叶斯对文本分类--对人名国别分类
网易云信 2022Q2 产品补给站,快来获取你的产品补给计划吧!