允许重新申请?

时间:2016-06-07 13:12:38

标签: c++

我发现了一个奇怪的错误(如果这确实是一个bug)。您可以稍后在同一范围内重新声明变量,而您已经可以使用第一个相同的命名变量。这是正常的吗?

此代码编译并正常运行,没有任何错误/警告。我正在使用代码块编译g ++。

int main()
{
    int test = 0;
    if(1)
        int test = 0;
    return 0;
}

4 个答案:

答案 0 :(得分:3)

此代码:

if(1)
    int test = 0;

等于:

if(1){
    int test = 0;
}

所以它是范围部分。 test内的if与范围外的test不同。

您可以访问外部int main() { int test = 0; if(1){ int test = 5; std::cout << "Inner:" << test<< "\n"; //you can not access the outer test } return 0; } 变量。

@Directive({
  selector: '[my-directive]',
})
class MyDirective {
  public directiveProperty = 'hi!';
}

答案 1 :(得分:2)

他们不在同一范围内。你并没有将花括号括在一个语句(而不是复合词) statement_true 并不意味着if没有创建新的范围。

请参阅:http://en.cppreference.com/w/cpp/language/if

答案 2 :(得分:2)

请尝试以下操作,以查看if是否创建了新范围:

int main()
{
    int test = 0;
    if(1)
        int test = 1;
    cout << test;
    return 0;
}

所以这不是一个错误,它是specification

答案 3 :(得分:1)

该标准允许相同的命名变量存在于不同的范围中,并且它定义了在范围内使用它们时将引用哪个变量的规则。相同的命名变量将隐藏(阴影)更高级别范围的变量。

L.E:Variable Shadowing