C++ 在函数中用static定义的变量的

来源:互联网 发布:比特彗星监听端口 编辑:程序博客网 时间:2024/05/22 05:59

在C++中,在函数中使用static定义一个变量,该变量最终只会分配一次内存,如果下次继续调用该函数,不会再重新分配内存给变量,而是使用上次分配的内存。

#include<iostream>using namespace std;class StaticVer{public:    int num ;    StaticVer():num(10){}};int * staticNum(){    static int a = 10;    return &a;}StaticVer * StaticObj(){    static StaticVer statv;    return &statv;}int main(void ){    for (size_t i = 0; i < 10; i++)    {        int *pNum = staticNum();        StaticVer*pObj = StaticObj();        cout << "staticNum addr:" << pNum << endl;        cout << "StaticObj addr:" << pObj << endl;        cout << "-------------------" << endl;    }    getchar();}

运行这段代码,我们会得到如下结果:

staticNum addr 总是指向地址0094E000
StaticObj addr 总是指向地址0094E2C8

staticNum addr:0094E000StaticObj addr:0094E2C8

最后程序运行截图
这里写图片描述

0 0