In C++, what is the scope resolution ("order of precedence") for shadowed variable names? I can't seem to find a concise answer online.
For example:
#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();
}
I can't think of any other scopes where a variable might conflict. Please let me know if I missed one.
What is the order of priority for all four shadow
variables when inside the bar
member function?
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.
来源:https://stackoverflow.com/questions/2804880/in-c-what-is-the-scope-resolution-order-of-precedence-for-shadowed-variab