【问题标题】:Names denoted the same entity名称表示同一实体
【发布时间】:2014-05-15 03:41:33
【问题描述】:

声明性区域的如下定义:

每个名称都在程序文本的某些部分中引入,称为 声明区域,它是程序的最大部分,其中 该名称是有效的,也就是说,该名称可以用作 非限定名称来指代同一实体。

我们在下面的规范中有示例:

int j = 24;
int main() {
    int i = j, j;
    j = 42;
}

标识符 j 被声明为名称两次(并使用了两次)。这 第一个 j 的声明区域包括整个示例。这 第一个 j 的潜在范围紧接在那个 j 之后开始,并且 延伸到程序的末尾,但其(实际)范围不包括 和 } 之间的文本。第二个声明区域 j 的声明(分号前的 j)包括所有 { 和 } 之间的文本,但其潜在范围不包括 i 的声明。 j的第二个声明的范围是一样的 作为它的潜在范围。

目前还不清楚如何确定任意名称的声明区域。至少我在标准中找不到这个。

【问题讨论】:

    标签: c++ scope declaration


    【解决方案1】:

    在文件范围内(即不在命名空间、类或函数内)声明的变量的潜在范围是从声明变量的点到文件末尾。在函数内声明的变量的潜在作用域是从声明变量的点到声明变量的右大括号。

    如果在某个内部范围内声明了同名的新变量,则变量的实际范围可能小于潜在范围。这称为阴影

    // The following introduces the file scope variable j.
    // The potential scope for this variable is from here to the end of file.
    int j = 42; 
    
    // The following introduces the file scope variable k.
    int k = 0;
    
    // Note the parameter 'j'. This shadows the file scope 'j'.
    void foo (int j) 
    {
        std::cout << j << '\n'; // Prints the value of the passed argument.
        std::cout << k << '\n'; // Prints the value of the file scope k.
    }
    // The parameter j is out of scope. j once again refers to the file scope j.
    
    
    void bar ()
    {
        std::cout << j << '\n'; // Prints the value of the file scope j.
        std::cout << k << '\n'; // Prints the value of the file scope k.
    
        // Declare k at function variable, shadowing the file scope k.
        int k = 1; 
        std::cout << k << '\n'; // Prints the value of the function scope k.
    
        // This new k in the following for loop shadows the function scope k.
        for (int k = 0; k < j; ++k) { 
            std::cout << k << '\n'; // Prints the value of the loop scope k.
        }
        // Loop scope k is now out of scope. k now refers to the function scope k.
    
        std::cout << k << '\n'; // Prints the function scope k.
    }
    // Function scope k is out of scope. k now refers to the file scope k.
    

    【讨论】:

    • 那么声明区域的定义是什么?
    • 变量的声明区域是该变量的潜在范围减去该变量被遮蔽的区域。
    • 但在 N3797 草案 3.3/2 示例中暗示 The declarative region of the first j includes the entire example.
    • The declarative region of a variable is the potential scope of that variable less the region where the variable is shadowed. 这不是真的,因为Every name is introduced in some portion of program text called a declarative region, which is the largest part of the program in which that name is valid
    • 这肯定是真的。非限定变量名称指的是变量被遮蔽的区域中的不同实体。您截断了定义的关键部分。引用,强调我的,“......该名称有效的程序的最大部分,也就是说,该名称可以用作引用同一实体的非限定名称。 "
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 2014-01-19
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多