01 Basic Concepts
Static members: the previously defined keywords add a static member.
class A
{
public:
A(int a, int b):m_a(a),m_b(b)
{
num += m_a + m_b;
}
~A(){ }
void Fun(); // 普通成员函数
static void PrintNum() // 静态成员函数
{
// 在静态成员函数中,不能访问非静态成员变量,也不能调用非静态成员函数
std::cout << num << std::endl;
}
private:
int m_a; // 普通成员变量
int m_b; // 普通成员变量
static int num; // 静态成员变量
};
// 静态成员必须在定义类的文件中对静态成员变量进行初始化,否则会编译出错。
int A::num = 0;
int main()
{
A a1(1,1);
A::PrintNum(); // 访问静态函数
A a2(1,1);
A::PrintNum(); // 访问静态函数
return 0;
}
Output
2
4
- Ordinary member variables of each object has its own copy, while static member variables of a total of one, shared by all objects.
It should be noted that the sizeof
operator does not calculate the static member variable size, chestnut follows:
class CTest
{
int n;
static int s;
};
It is sizeof(CTest)
equal to 4
- Ordinary members have specific functions act on an object, and the static member function not specifically act on an object .
- So static members do not need to be able to visit through the object to ask, because he is shared.
02 How to access static members
1) the class name :: Member Name
A::PrintNum();
2) object name. Member Name
A a;
a.PrintNum();
3) pointer -> member name
A *p = new A();
p->PrintNum();
4) references. Member Name
A a;
A & ref = a;
ref.PrintNum();
03 Summary
- It is a static member variable nature of global variables, even if an object does not exist, like static member variables there.
- Function on a global function is essentially a static member.
- Set a static member of such a mechanism is the purpose of global variables and functions and some closely related write in the class inside, looks like a whole, easy to maintain and understand.
- In the static member function, you can not access non-static member variables, we can not call non-static member functions.
- Static members must be initialized static member variables in a class definition file, otherwise it will compile error.