注册 登录
编程论坛 C++教室

[求助]请教访问隐藏名称的问题

叮叮当 发布于 2007-03-26 19:07, 431 次点击
大家好,我在看c++的书的时候,用::访问隐藏的名称,却总是编译出错,提示“has not been ceclared”,请问一下是哪里错了或该如何解决

#include <iostream>
using std::cout;
using std::endl;

int main() {
const int limit=10;
cout<<"outer limit is "<<limit<<endl;
{
const int limit=5;
cout<<"inner limit is "<<limit<<endl;
for(int i=1; i<=::limit; i++) //这一行不能通过编译
cout<<endl<<i<<"squared is "<<i*i;
}
cout<<endl<<endl<<"last limit is "<<limit<<endl;
system("pause");
return 0;
}
2 回复
#2
yuyunliuhen2007-03-26 19:25
#include <iostream>
using std::cout;
using std::endl;
const int limit=5;
int main() {
const int limit=10; //全局变量
cout<<"outer limit is "<<limit<<endl;
{
// const int limit=5;
cout<<"inner limit is "<<limit<<endl;
for(int i=1; i<=::limit; i++) //可以通过作用域解析符::可以访问全局变量,
//而你将它定义的是个局部变量
cout<<endl<<i<<"squared is "<<i*i;
}
cout<<endl<<endl<<"last limit is "<<limit<<endl;
system("pause");
return 0;
}

#3
叮叮当2007-03-26 20:07
原来::这个表达式只能访问全局变量,而不能访问比当前高一级的局部变量~是这样的吧
在main外面多加一个全局变量就通过编译了
谢谢您!
1