在C ++中,同一个名称的两个变量何时在同一范围内可见? [英] In C++, when can two variables of the same name be visible in the same scope?

查看:183
本文介绍了在C ++中,同一个名称的两个变量何时在同一范围内可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码说明了我认为应该被视为不良做法的事情,并从编译器获取有关重新定义或屏蔽变量的警告:

This code illustrates something that I think should be treated as bad practice, and elicit warnings from a compiler about redefining or masking a variable:

#include <iostream>

int *a;

int* f()
{
  int *a = new int;
  return a;
}

int main()
{
  std::cout << a << std::endl << f() << std::endl;
  return 0;
}

其输出(使用g ++编译):

Its output (compiled with g++):

0
0x602010

我看了几个引用(Stroustrup和完整的C ++引用),并找不到任何关于什么时候和为什么这是允许的。我知道它不在一个单一的本地范围内,

I've looked at a couple references (Stroustrup and The Complete C++ Reference) and can't find anything about when and why this is allowed. I know that it's not within a single local scope, though.

这是允许什么时候为什么?这个结构有很好的用处吗?我怎么能让g ++警告我呢?

When and why is this allowed? Is there a good use for this construct? How can I get g++ to warn me about it? Do other compilers squawk about it?

推荐答案

允许您安全地忽略全局标识符覆盖。基本上,你只需要关心你实际使用的全局名称。

It's allowed so that you can safely ignore global identifier overriding. Essentially, you only have to be concerned with global names you actually use.

假设在您的示例中,首先定义了 f()。然后一些其他开发人员添加了全局声明。通过添加一个名称, f()以前工作,仍然可以工作。如果覆盖是一个错误,那么函数会突然停止工作,即使它对新添加的全局变量没有做任何事情。

Suppose, in your example, f() had been defined first. Then some other developer added the global declaration. By adding a name, f() which used to work, still works. If overriding was an error, then the function would suddenly stop working, even though it doesn't do anything at all with the newly added global variable.

这篇关于在C ++中,同一个名称的两个变量何时在同一范围内可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆