我在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.
}
}
我知道::操作符的确在使用它的语句时用Global覆盖了local的优先级,但我想在一个块级别上使用它。请帮我。我也在书本和互联网上看到了一些参考文献,实际上我确实做了反向(首先是在互联网上,然后在书本上),但我无法弄清楚。请帮我。
我的原始代码是:
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 %d\n", max, m_max, ::max); // have to use alias name :(
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句