[C++] 作用域问题
以C++ Primer 3rd ed 习题8.1为例分析:
#include<iostream>
using namespace std;
int ix = 1024;// global scope
int ix();// 1 error: 'int ix()' redeclared as different kind of symbol
void func( int ix, int iy ){ //local scope 1
int ix = 255;// 2 error: declaration of 'int ix' **shadows** a parameter
if ( int ix = 0 ){ //3 error: redeclaration of 'int ix' note: 'int ix' previously declared here //local scope 2
int ix = 79;//local scope 3
{
int ix = 89; //local scope 4
}
}
else{
int ix = 99;//local scope 5
}
//cout<<"ix: "<<ix<<endl;
}
//int main(){
// return 0;
//}
要求指出不同的域,哪些声明是错误的。
答:
1. error: 'int ix()' redeclared as different kind of symbol
不同类型也不能重名,这也同时回答了一个问题--函数名、变量名、类名、结构名可以重名吗?
答案是,在同一个域下不能重名。这里都是全局域因此重名了。当然,重载函数是个例外(但他们参数也不同)。
2. error: declaration of 'int ix' **shadows** a parameter
百度了一下,这里的 shadow 应该被翻译为隐藏了,或者说挡住了,即这个 ix 把传参进来的 ix 给隐藏了。
同时这也回答了另一个问题,局部变量可以和参数名一样吗?显然答案是不可以。
3.error: redeclaration of 'int ix'
note: 'int ix' previously declared here
我们知道较外层的域的命名在嵌入的域里也是有效的,但是嵌入域*可以*定义域外层域相同的命名,同时在自己的域里会覆盖那个相同的名字。这里的redeclaration of 'int ix' 指的是 local scope 3里的ix,和if条件里定义的ix重名了,同时提醒,ix已经定义了。local scope 5 同理。在我的编译器下,如果if括号判断里没有定义ix,那么在if{}和else{}中分别定义ix都是可以的,结合上面来说,就是if括号里的条件与if{}和else{}分别属于同一个域,但是if{}和else{}两个却独立属于两个域。