什么是外部联系和内部联系?我想了解一下对外联系和内部联系及其区别。我也想知道const默认情况下,变量内部链接,除非另有声明为extern.
3 回答
![?](http://img1.sycdn.imooc.com/5458683f00017bab02200220-100-100.jpg)
慕少森
TA贡献2019条经验 获得超9个赞
.cpp
, .cxx
#include
内部联动
外部联动
![?](http://img1.sycdn.imooc.com/54584cde0001d19202200220-100-100.jpg)
四季花海
TA贡献1811条经验 获得超5个赞
extern
static
extern
const
static
const
// in namespace or global scopeint i; // extern by defaultconst int ci; // static by defaultextern const int eci; // explicitly externstatic int si; // explicitly static// the same goes for functions (but there are no const functions)int foo(); // extern by defaultstatic int bar(); // explicitly static
static
class
namespace { int i; // external linkage but unreachable from other translation units. class invisible_to_others { };}
![?](http://img1.sycdn.imooc.com/54584dd900014f6c02200220-100-100.jpg)
红颜莎娜
TA贡献1842条经验 获得超12个赞
全局变量 外部联动
默认情况下。它的作用域可以扩展到文件,而不是通过提供匹配来包含它。 外露
在另一个文件中声明。 全局变量的作用域可以限制为包含其声明的文件,方法是以关键字作为声明的前缀。 静态
..这些变量据说有 内部联动.
1.cpp
void f(int i);extern const int max = 10;int n = 0;int main(){ int a; //... f(a); //... f(a); //...}
函数f的签名将f声明为具有 外部联动
(默认)其定义必须在本文件后面或其他翻译单位中提供(如下所示)。 MAX被定义为整数常量。常量的默认链接是 内部
..它的链接用关键字更改为外部。 外露
..所以现在max可以在其他文件中访问。 N被定义为整数变量。外部函数体定义的变量的默认链接是 外部.
2.cpp
#include <iostream>using namespace std;extern const int max;extern int n;static float z = 0.0;void f(int i){ static int nCall = 0; int a; //... nCall++; n++; //... a = max * z; //... cout << "f() called " << nCall << " times." << endl;}
马克斯被宣布 外部联动
..max的匹配定义(具有外部链接)必须出现在某个文件中。(如1.cpp所示) N被宣布为 外部联动.
Z是 定义
作为全局变量 内部联动.
nCall的定义指定nCall是一个在函数f()的调用中保留其值的变量。与具有默认自动存储类的局部变量不同,nCall在程序开始时只初始化一次,而不对f()的每次调用初始化一次。存储类说明符 静态
影响局部变量的生存期,而不是其作用域。
注:
- 3 回答
- 0 关注
- 1580 浏览
添加回答
举报
0/150
提交
取消