1.静态成员变量需要在类外分配空间,类外不要用static
2.静态成员函数只能访问静态成员函数和静态成员变量,没有this指针
3.静态成员是整个类共有的,通过对象名和类名都可以访问,不计入类的字节数
#include <iostream>
using namespace std;
#include <string>
class Person
{
public:
Person(int a) :m_A(a) {}
int m_A;
static int m_B;
static void show()
{
cout <<"静态成员函数show的调用m_B="<< m_B << endl;//静态成员函数访问静态成员变量
}
static void fun()
{
cout << "静态成员函数fun的调用" << endl;
show();//静态成员函数调用静态成员函数
}
};
int Person::m_B = 10;//类外分配空间,在全局区
int main()
{
Person p(15);
p.fun();//对象调用
Person::fun();//类名调用
cout << sizeof(p) << endl;
return 0;
}
运行结果:
静态成员函数fun的调用
静态成员函数show的调用m_B=10
静态成员函数fun的调用
静态成员函数show的调用m_B=10
4
类结构:
class Person size(4):
+---
0 | m_A
+---