本文PDF下载站点: https://github.com/MrWang522/Private-Document.git
1. 函数中的静态变量
- 要点: 与C一样
- 描述: 函数中的static变量,在 程序 的生命周期内分配, 且只初始化一次!
void demo() {
static int count = 0;
cout << count << " ";
count++;
}
void Test() {
for (int i=0; i<5; i++) demo(); // 打印 0 1 2 3 4
}
2. 类中的静态变量
- 类中的静态变量 对象共享
- 静态变量 不能使用 构造函数初始化 (相同类中的 静态变量 是共享的)
class MyClass{
public:
static int i;
MyClass(){
// Do nothing
};
};
int Apple::i = 1; // 静态变量 只能在外部 初始化
void function() {
MyClass obj1, obj2;
obj2.i = 3;
obj2.i = 2;
cout << obj1.i; // 打印2 相同类中的 静态变量 是共享的
}
3. 类中的静态函数
- 类中的静态成员函 没有this指针
- 在类外(或通过对象调用)调用静态成员函数用 “类名:: ” 作限定词
class MyClass{
public:
static void printMsg() {
cout<<"Welcome to Apple!";
}
};
void function() {
MyClass::printMsg();
}
重点: 类中的静态成员函数内,不能使用类中的普通变量,否则编译器报错 !!!
class MyClass{
int x; // 普通变量
static int i; // 静态变量
public:
MyClass():x(100){}
static void tFun() {
cout << "i = " << i << endl; // 正常使用
cout << "x = " << x << endl; // 此处编译器报错 !!! EO245 非静态成员引用必须与特定对象相对
}
};
int MyClass::i = 200; // 这里是 让编译器 分配内存!!!!
void Test() {
MyClass obj;
obj.tFun();
}