您的位置:首页 > 编程语言 > C语言/C++

c++中关键字static在普通变量及函数详解及实例运行答案

2017-12-19 16:23 911 查看
静态全局变量
例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;
}


运行结果出错

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐