在C++中,阴影变量名称的范围分辨率("优先顺序")是多少?

Emi*_*ier 16 c++ variables scope scope-resolution shadowing

在C++中,阴影变量名称的范围分辨率("优先顺序")是多少?我似乎无法在网上找到简明的答案.

例如:

#include <iostream>

int shadowed = 1;

struct Foo
{
    Foo() : shadowed(2) {}

    void bar(int shadowed = 3)
    {
        std::cout << shadowed << std::endl;
            // What does this output?

        {
            int shadowed = 4;
            std::cout << shadowed << std::endl;
                // What does this output?
        }
    }

    int shadowed;
};


int main()
{
    Foo().bar();
}
Run Code Online (Sandbox Code Playgroud)

我想不出变量可能会发生冲突的任何其他范围.如果我错过了,请告诉我.

shadowbar成员函数内部时,所有四个变量的优先级顺序是多少?

Bil*_*eal 31

你的第一个例子输出3.你的第二个输出4.

一般的经验法则是查找从"最本地"变量到"最小本地"变量.因此,优先级是block - > local - > class - > global.

您还可以显式访问每个大多数版本的阴影变量:

// See http://ideone.com/p8Ud5n
#include <iostream>

int shadowed = 1;

struct Foo
{
    int shadowed;
    Foo() : shadowed(2) {}
    void bar(int shadowed = 3);
};

void Foo::bar(int shadowed)
{
    std::cout << ::shadowed << std::endl; //Prints 1
    std::cout << this->shadowed << std::endl; //Prints 2
    std::cout << shadowed << std::endl; //Prints 3
    {
        int shadowed = 4;
        std::cout << ::shadowed << std::endl; //Prints 1
        std::cout << this->shadowed << std::endl; //Prints 2
        //It is not possible to print the argument version of shadowed
        //here.
        std::cout << shadowed << std::endl; //Prints 4
    }
}

int main()
{
    Foo().bar();
}
Run Code Online (Sandbox Code Playgroud)


Jer*_*fin 5

它应该打印出3.基本规则主要是通过文件向后工作到编译器可能看到的最新定义(编辑:没有超出范围),这就是它的用途.对于类的本地变量,除了将所有类变量视为在类定义的开头定义它们之外,遵循相同的变量.请注意,这对于类来说或多或少是唯一的.例如,给定代码如:

int i;

int x() { 
    std::cout << i << '\n'; // prints 0;
    int i=1;
}
Run Code Online (Sandbox Code Playgroud)

即使一个i局部于功能,最近的定义在哪里见过cout则采用的是全球性的,所以这是什么i在表达指.但是,如果这是在课堂上:

int i;

class X { 
    void y() { std::cout << i << "\n"; }

    X() : i(2) {}

    int i;
};
Run Code Online (Sandbox Code Playgroud)

然后cout表达式将引用X::i即使y在解析时尚未看到它的定义.