c++语言中的块作用域解析
block scope resolution in c++ language
我正在做一个c++程序的练习,我在这里发布了这个程序的一部分,它给了我问题
int max=100;
main()
{ int max=50;
{
int max=25;
printf("%d",max);
printf("%d",::max);
//output will be 25 and 100
// I wanted to use value "50" of max in this block i.e. the max variable of above block which is local to main
// and I can't figure out how to do this.
}
}
我知道::操作符确实覆盖了local与Global的优先级,用于它所使用的语句,但我想为一个块级别做它。请帮帮我。我在书和网上也看到了一些参考资料,实际上我做了反向(首先在网上,然后在书中),但我不能弄清楚。请帮我一下。
我的原始代码是:
int max=100;
void main()
{
int max=50;
char str[50];
gets(str);
if(strlen(str)>5)
{
int max=25;
cout<<"Max here is"<<max<<endl;
cout<<"Max above was"<</*max value of above block*/;
cout<<"Max Global"<<::max;
}
}
这不可能。内部局部作用域完全遮蔽外部嵌套作用域名称。
你能做的最好的事情是在遮蔽外部名称之前创建一个别名:
int max = 100;
int main() {
int max = 50;
{
int &m_max = max; // make reference alias first!
int max = 25;
printf("%d %d %dn", max, m_max, ::max); // have to use alias name :(
}
}
不能在内部块中对变量max visible进行第二次声明,因为内部块中具有相同名称的变量隐藏了它。只能对在名称空间或类作用域中声明的变量使用限定名。在您的示例中,您使用限定名::max
来访问在全局命名空间中声明的变量。
相关文章:
- C++具有不同作用域的相同名称的名称解析规则
- 用于返回嵌套类类型的作用域解析运算符
- 今天的主流编程语言主要使用动态还是静态(词汇)作用域?
- 变量声明中结构的作用域解析是什么意思
- 模板类中静态函数或指针的作用域解析
- 作用域解析运算符和常量
- 模板子类作用域解析
- ::(作用域解析运算符)在C++中用于多种用途
- 使用指向成员的指针时,如何通过作用域解析运算符获取类成员的地址
- 带有继承的C++作用域解析用法
- ::c++中模板函数调用前面的作用域解析运算符
- 为什么作用域解析对覆盖的变量不起作用?
- isalnum的作用域解析运算符
- c++新内存替换和作用域解析
- 为什么c++的作用域解析操作符是::
- ::操作符能否出现在与限定名查找中的作用域解析不同的上下文中?
- c++语言中的块作用域解析
- 在类定义的类名中,作用域解析操作符的作用是什么?
- 关于c++中作用域解析操作符的问题
- 为什么基类构造函数没有被作用域解析操作符调用