作用域是程序内的一个区域,在这个区域内名字有特定的含义。c++中的大多数作用域都是以大括号分隔。
下面是示例代码,在官方代码的基础上做了稍许改动
1 #include <iostream> 2 3 // 本程序仅用于演示目的 4 5 int reused = 42; // reused 具有全局作用域 6 7 int main() 8 {//开始执行时,只有全局作用域的名称::resued和main是可访问的 9 int unique = 0; // unique 具有块作用域 10 11 // output #1: 使用全局变量 reused; 打印 42 0 12 std::cout << reused << " " << unique << std::endl; 13 14 int reused = 0; // 新建的局部变量 reused 覆盖了全局变量 reused 15 16 // output #2: 使用局部变量 reused; 打印 0 0 17 std::cout << reused << " " << unique << std::endl; 18 19 // output #3: 显式的使用全局变量 reused; 打印 42 0 20 std::cout << ::reused << " " << unique << std::endl; 21 if(true) 22 { 23 int var1 = 9; 24 std::cout << var1 <<std::endl; 25 } 26 return 0; 27 }
上述代码的运行演示视频:https://www.bilibili.com/video/av82419597/