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

静态全局变量

例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;
}

运行结果出错








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值