static
用法
修饰普通变量:static
关键字可用于修改普通变量的存储区域和生命周期,使其存储在静态区,在程序运行前就分配了空间。如果有初始值,将使用初始值进行初始化,否则系统会用默认值初始化它。 修饰普通函数:static
关键字可用于限制函数的作用范围,使其仅在定义该函数的文件内可用。这有助于防止在多人协作项目中与其他命名空间中的函数重名。 修饰成员变量:在类中,static
关键字可用于修饰成员变量,使得所有的类对象只保存一个该变量的副本,而且不需要生成对象就可以访问该成员。 修饰成员函数:static
关键字可用于修饰成员函数,使得不需要生成对象就可以访问该函数。但需要注意,在静态函数内部不能访问非静态成员,因为它没有类对象的上下文。
代码示例:
# include <iostream>
void countCalls ( ) {
static int count = 0 ;
count++ ;
std:: cout << "Function has been called " << count << " times." << std:: endl;
}
static int globalVar = 42 ;
class MyClass {
public :
static int staticVar;
static void staticFunction ( ) {
std:: cout << "This is a static member function." << std:: endl;
}
} ;
int MyClass:: staticVar = 0 ;
int main ( ) {
countCalls ( ) ;
countCalls ( ) ;
countCalls ( ) ;
std:: cout << "Global variable: " << globalVar << std:: endl;
MyClass obj1;
MyClass obj2;
obj1. staticVar = 1 ;
obj2. staticVar = 3 ;
std:: cout << "obj1.staticVar: " << obj1. staticVar << std:: endl;
std:: cout << "obj2.staticVar: " << obj2. staticVar << std:: endl;
std:: cout << "MyClass::staticVar: " << MyClass:: staticVar << std:: endl;
MyClass :: staticFunction ( ) ;
return 0 ;
}
输出结果:
Function has been called 1 times.
Function has been called 2 times.
Function has been called 3 times.
Global variable: 42
obj1.staticVar: 3
obj2.staticVar: 3
MyClass::staticVar: 3
This is a static member function.