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
原创粉丝点击