c++中的static变量
来源:互联网 发布:使用sysprep 恢复数据 编辑:程序博客网 时间:2024/05/19 02:16
1)当函数中的局部变量为static时
此变量只在函数第一次被调用时初始化,函数调用之间保持变量的值不变。那为什么不使用全局变量呢?static变量的优点是在函数的范围之外它是不可用的。e.g.:
#include <iostream>
using namespace std;
void f()
{
static int si=0;//此句只会被执行一次
cout << "si=" << ++si << endl;
}
int main()
{
for(int i=0; i<10; i++)
f();
}
output如下:
si=1
si=2
...
si=10
2)static的另一层含义是:“在某个作用域外不可访问”
当应用static于函数名和所有函数外部的变量时,它的意思是“在文件的外部不可以使用这个名字”。函数名或变量是局部于文件的;我们说它具有文件作用域(file scope)。e.g.,编译和连接下面两个文件会引起连接器错误:
// file1
static int fs;
// file scope means only available in this file:
int main()
{
fs = 1;
}
// file2
extern int fs; // trying to reference fs
void func()
{
fs = 1000;
}
3)static也可以在一个类中
此变量只在函数第一次被调用时初始化,函数调用之间保持变量的值不变。那为什么不使用全局变量呢?static变量的优点是在函数的范围之外它是不可用的。e.g.:
#include <iostream>
using namespace std;
void f()
{
static int si=0;//此句只会被执行一次
cout << "si=" << ++si << endl;
}
int main()
{
for(int i=0; i<10; i++)
f();
}
output如下:
si=1
si=2
...
si=10
2)static的另一层含义是:“在某个作用域外不可访问”
当应用static于函数名和所有函数外部的变量时,它的意思是“在文件的外部不可以使用这个名字”。函数名或变量是局部于文件的;我们说它具有文件作用域(file scope)。e.g.,编译和连接下面两个文件会引起连接器错误:
// file1
static int fs;
// file scope means only available in this file:
int main()
{
fs = 1;
}
// file2
extern int fs; // trying to reference fs
void func()
{
fs = 1000;
}
3)static也可以在一个类中
- c中的static变量
- C语言中的static变量
- C语言中的 static变量、static函数
- C语言中的 static变量、static函数
- C语言中的 static变量、static函数
- C语言中的 static变量、static函数
- C语言中的static变量 和 C++中static变量
- C/C++中的static变量和static函数
- c语言中的static变量和static函数
- C语言中的static前缀(static函数/变量)
- C语言中的static变量和static函数
- C/C++中的 static 变量和 static 函数
- C语言中的static变量和static函数
- c语言中的static变量和static函数
- c++中的static变量
- C++中的static变量
- C语言static变量
- [C++]static成员变量
- JBI规范1.0[4]——系统架构
- 瑞泰人寿上海分公司应松:投连险适合长期理财
- 关于字符串的总结
- 似水流年
- 用回ie6+sp1
- c++中的static变量
- 玩转“网上邻居”之故障分析
- 共享上网完全攻略
- 一时感触—刚走上工做岗位的我
- 不用.net和其组件用asp访问webservice
- 系统的运行级别
- Get和Post方式的区别!
- 八皇后算法
- 大学生一定要理解的15件事