表示同一实体的名称

2023-11-30

以下定义声明区域:

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

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

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

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

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


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

如果在某个内部作用域声明了同名的新变量,则变量的实际作用域可能小于潜在作用域。这就是所谓的影子.

// 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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

表示同一实体的名称 的相关文章

随机推荐