静态变量(Static Variable)在计算机编程领域指在程序执行前系统就为之静态分配(也即在运行时中不再改变分配情况)存储空间的一类变量。与之相对应的是在运行时只暂时存在的自动变量(即局部变量)与以动态分配方式获取存储空间的一些对象,其中自动变量的存储空间在调用栈上分配与释放。
静态变量的写法如下示例:
C示例
在C语言中,带有静态变量的程序如下所示:[1]
#include <stdio.h>void func() { static int x = 0; // 在对func的三次调用中,x只进行一次初始化 printf("%d\n", x); // 输出x的值 x = x + 1;}int main(int argc, char * const argv[]) { func(); // 输出0 func(); // 输出1 func(); // 输出2 return 0;}
C++示例
在C++中,带有含私有静态内部变量的类的程序如下所示:
class Request {
private:
static int count; // 不能为外部调用
string url; // 只能被成员函数调用
public:
Request()
{
count++;
}
string getUrl() const { return url; }
void setUrl(string value)
{
url = value;
}
static int getCount()
{
return count;
}
};
int Request::count = 0; // count