c++语言中的块作用域解析

block scope resolution in c++ language

本文关键字:作用域解析 语言 c++      更新时间:2023-10-16


我正在做一个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来访问在全局命名空间中声明的变量。