C++静态持续性之外部链接性---普通成员变量,变量单一定义规则和extern使用示例

一、单一定义规则

C++ 单定义规则 One Definition Rule ODR ),该规则指出,
变量只能有一次定义。为满足这种需求, C++ 提供了两种变量声明。一
种是定义声明(defining declaration)或简称为定义(definition),它给 变量分配存储空间;另一种是引用声明(referencing declaration)或简 称为声明(declaration),它不给变量分配存储空间,因为它引用已有 的变量。
引用声明使用关键字 extern ,且不进行初始化
注意:如果一个程序中同时存在多个相同的变量名,编译会报错,这时可以用如下方法避免:
1、使用extern 关键字
2、使用命名空间namespace
3、使用static修饰变量,static限定符使该变量被限制在这个文件内,并覆盖相应的全局定义(即使用static修饰的变量为内部链接,原理同2类似,限制范围)

二、使用示例

file1.cpp

#include <iostream>
int tom=3;

using namespace std;

int main()
{
    cout <<"file1.cpp &tom"<<&tom<<",,,,tom="<<tom<<endl;
    remote_access();
   cout <<"file1.cpp &tom"<<&tom<<",,,,tom="<<tom<<endl;
    return 0;
}

file2.cpp

#include <iostream>
extern int tom;
//extern int tom=5;//这里这样重新初始化编译会报错
//static int tom=4; //使用static修饰的变量,具有内部链接性,该变量限制在file2.cpp中使用,也可行


void remote_access()
{
    using namespace std;
    tom=5;//这样重新赋值可以,而且file1.cpp的tom变量值也被修改成了5
 
    cout <<"file2.cpp &tom"<<&tom<<",,,,tom="<<tom<<endl;
}

编译上面两个文件,g++  file1.cpp file2.cpp  -o  test

程序执行结果如下:

file1.cpp &tom0x403010,,,,tom=3
remote_access() reports the follwing addresses:
file2.cpp &tom0x403010,,,,tom=5
file1.cpp &tom0x403010,,,,tom=5

猜你喜欢

转载自blog.csdn.net/banzhuantuqiang/article/details/130910468