c++ - 在 C++ 中,阴影变量名称的范围分辨率 ("order of precedence"是什么?

标签 c++ variables scope shadowing scope-resolution

在 C++ 中,shadowed 的作用域解析(“优先顺序”)是什么?变量名?我似乎无法在网上找到简明的答案。

例如:

#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();
}

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

bar 成员函数中所有四个 shadow 变量的优先级顺序是什么?

最佳答案

您的第一个示例输出 3。您的第二个示例输出 4。

一般的经验法则是查找从“最局部”到“最不局部”变量。因此,这里的优先级是 block -> 本地 -> 类 -> 全局。

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

// 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();
}

关于c++ - 在 C++ 中,阴影变量名称的范围分辨率 ("order of precedence"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2804880/

相关文章:

java - 为什么我应该 "Transform myVariable to final one element array"?

c++ - 在泛型类之外定义函数会产生编译错误

c++ - 为什么使用 rbegin() 而不是 end() - 1?

java - 如何解决 'cannot find symbol'错误?

Javascript函数范围和查找父对象的属性

c++ - 头文件中的枚举

c++ - 在C++中,fscanf如何分配内存地址?

c++ - 将 vector<double> 转换为 vector<string> (优雅的方式)

java - 如何访问数组中的字段,字段名称存储在变量中?

javascript - 使用选择器作为变量循环 .append()