c++中关键字static在普通变量及函数详解及实例运行答案
来源:互联网 发布:泼墨字体生成软件 编辑:程序博客网 时间:2024/06/07 20:01
静态全局变量
例1 有无static无影响
c++代码
#include<iostream>using namespace std;static int n;//全局静态变量void func();int main(){ n=1; cout<<"主函数中的n为 "<<n<<endl;func();return 0;}void func(){ n++; cout<<"调用函数中的n为 "<<n<<endl;}
运行结果
例2 有无static有影响
静态全局变量不能被其它文件所用;
其它文件中可以定义相同名字的变量,不会发生冲突;main函数文件中
#include<iostream>#include<file.cpp>using namespace std;static int n;//全局静态变量void func();int main(){ n=1; cout<<"主函数中的n为 "<<n<<endl; func(); return 0;}
file.cpp文件中
#include<iostream>using namespace std;extern int n;//extern:若n没在当前文件或当前文件的其他位置,则可以在其他文件或其他文件的其他位置寻找void func(){ n++; cout<<"func函数中的n为 "<<n<<endl;}
结果报错
将static int n;改为int n;正确运行
例3 静态局部变量
不会每次调用都被初始化,只初始化一次
#include<iostream>using namespace std;void func();int main(){ for(int i=0;i<5;++i) func(); return 0;}void func(){ static int n=1;//静态局部变量 cout<<"func函数中的n为 "<<n<<endl; n++;}
运行结果
将static int n=1;变为int n=1;
运行结果
例4 静态函数
静态函数与静态全局变量类似,只能在当前文件中可用,不能被其它文件中使用这个静态函数
例1
#include<iostream>using namespace std;static void func();//静态函数int main(){ func(); return 0;}void func(){ int n=1; cout<<"func函数中的n为 "<<n<<endl;}
运行结果
例5
main函数文件中
#include<iostream>#include<file.cpp>using namespace std;static void func();//静态函数int main(){ func(); return 0;}
file文件中
#include<iostream> usingnamespacestd; voidfunc(){ intn=1; cout<<"func函数中的n为"<<n<<endl;}
运行结果出错
阅读全文
0 0
- c++中关键字static在普通变量及函数详解及实例运行答案
- c++中关键字static在class类变量及函数详解及实例运行答案
- C/C++中static关键字及变量存储位置总结
- static作用(修饰函数、局部变量、全局变量) C/C++中static关键字详解
- c语言中内存及static详解
- static关键字及变量存储位置总结
- c++CreateEvent函数在多线程中使用及实例
- c++CreateEvent函数在多线程中使用及实例
- c++CreateEvent函数在多线程中使用及实例
- c++CreateEvent函数在多线程中使用及实例
- c++CreateEvent函数在多线程中使用及实例
- c++CreateEvent函数在多线程中使用及实例
- c++CreateEvent函数在多线程中使用及实例
- C语言中static关键字的常见用法及举例
- [关键字]C/C++中static关键字详解
- java中的static关键字详解及面试
- static全局变量/全局变量,static函数/普通函数,函数中static变量/函数中的变量,类中的static成员变量/普通类成员变量
- C语言函数内static关键字详解
- zookeeper docker集群配置
- HTML5魔法堂:全面理解Drag & Drop API
- vue-浏览器缓存
- luoguP2387 [NOI2014]魔法森林(LCT+并查集)
- 大数据正式28
- c++中关键字static在普通变量及函数详解及实例运行答案
- pat乙1012
- Python教程
- java对象参数传递相关问题
- 动态规划-用金矿模型用通俗的语言讲解
- (OK) android-x86-7.1-rc2
- Centos6.3下rsync+inotify服务器数据同步(备份)
- fiddler扩展模拟弱网络环境设置
- input输入框My97时间插件与值得获取