In C++, what is the scope resolution (“order of precedence”) for shadowed variable names?

半世苍凉 提交于 2019-11-29 01:25:36
Billy ONeal

Your first example outputs 3. Your second outputs 4.

The general rule of thumb is that lookup proceeds from the "most local" to the "least local" variable. Therefore, precedence here is block -> local -> class -> global.

You can also access each most versions of the shadowed variable explicitly:

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

It should print out 3. The basic rule is mostly to work your way backward through the file to the most recent definition the compiler would have seen (edit: that hasn't gone out of scope), and that's what it uses. For variables that are local to a class, you follow the same except that all class variables are treated as if they were defined at the beginning of the class definition. Note that this is more or less unique to classes though. For example, given code like:

int i;

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

Even though there is an i that's local to the function, the most recent definition seen where cout is used is the global, so that's what the i in that expression refers to. If, however, this were in a class:

int i;

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

    X() : i(2) {}

    int i;
};

Then the cout expression would refer to X::i even though its definition hasn't been seen yet when y is being parsed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!