当前位置: 代码迷 >> 综合 >> 函数生命期 (Updata later)
  详细解决方案

函数生命期 (Updata later)

热度:54   发布时间:2023-12-28 01:46:58.0

static

在全局作用域中,变量或函数实体若使用static修饰,则该实体对于其他源文件是屏蔽的,亦可成为private的。

函数定义前加static修饰,则函数成为内部函数。仅仅在包含它的文件中是有效的。

static声明静态局部变量会保持其值。

#include<iostream>
using namespace std;
int fun() {static int cnt = 0;cnt++;return cnt;
}
int main() {for (int i = 0; i < 10; i++) cout << fun() << " ";return 0;
}
// Output: 1 2 3 4 5 6 7 8 9 10
// If not use static
// Output: 1 1 1 1 1 1 1 1 1 1

extern

使用extern声明可以将函数或者变量的可见区域往前延伸,即为前置声明(forward declaration)。

在函数定义前面加extern声明,则称函数为外部函数,但在C++中所有函数本质上都是外部函数,因此extern通常省略(可以理解为除了static声明函数之外,其余函数均为外部函数)。