#include<iostream>intmain(){// outer blockintapples{5};// here's the outer block apples{// nested block// apples refers to outer block apples herestd::cout<<apples<<'\n';// print value of outer block apples// no inner block apples defined in this exampleapples=10;// this applies to outer block applesstd::cout<<apples<<'\n';// print value of outer block apples}// outer block apples retains its value even after we leave the nested blockstd::cout<<apples<<'\n';// prints value of outer block applesreturn0;}// outer block apples destroyed
执行上述代码,打印结果如下:
123
5
10
10
在内层嵌套块中,是没有办法直接访问已经被临时屏蔽的外层变量的。
全局变量的遮蔽
当局部变量和全局变量重名时,它也会在局部变量的作用域中奖全局变量临时屏蔽:
1 2 3 4 5 6 7 8 91011121314151617181920
#include<iostream>intvalue{5};// global variablevoidfoo(){std::cout<<"global variable value: "<<value<<'\n';// value is not shadowed here, so this refers to the global value}intmain(){intvalue{7};// hides the global variable value until the end of this block++value;// increments local value, not global valuestd::cout<<"local variable value: "<<value<<'\n';foo();return0;}// local value is destroyed
#include<iostream>intvalue{5};// global variableintmain(){intvalue{7};// hides the global variable value++value;// increments local value, not global value--(::value);// decrements global value, not local value (parenthesis added for readability)std::cout<<"local variable value: "<<value<<'\n';std::cout<<"global variable value: "<<::value<<'\n';return0;}// local value is destroyed