In C++, what is the scope resolution (quot;order of precedencequot;) for shadowed variable names?(在 C++ 中,阴影变量名称的范围解析(“优先顺序)是什么?)
问题描述
在 C++ 中,shadowed 变量的范围解析(优先顺序")是什么名字?我似乎无法在网上找到简明的答案.
In C++, what is the scope resolution ("order of precedence") for shadowed variable names? I can't seem to find a concise answer online.
例如:
#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.
bar
成员函数中所有四个 shadow
变量的优先级顺序是什么?
What is the order of priority for all four shadow
variables when inside the bar
member function?
推荐答案
您的第一个示例输出 3.您的第二个输出 4.
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();
}
这篇关于在 C++ 中,阴影变量名称的范围解析(“优先顺序")是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中,阴影变量名称的范围解析(“优先顺序")是什么?


基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30