Is there any way to access a local variable in outer scope in C++?(有没有办法在 C++ 中访问外部作用域中的局部变量?)
问题描述
只是出于好奇:如果我有嵌套的作用域,就像在这个示例 C++ 代码中一样
Just out of curiosity: if I have nested scopes, like in this sample C++ code
using namespace std;
int v = 1; // global
int main (void)
{
int v = 2; // local
{
int v = 3; // within subscope
cout << "subscope: " << v << endl;
// cout << "local: " << v << endl;
cout << "global: " << ::v << endl;
}
cout << "local: " << v << endl;
cout << "global: " << ::v << endl;
}
有没有办法从中间"范围(非全局或本地)访问变量 v
的值 2
?
Is there any way to access the variable v
with the value 2
from the "intermediate" scope (neither global nor local)?
推荐答案
你可以像这样声明一个新的引用作为别名
You can declare a new reference as an alias like so
int main (void)
{
int v = 2; // local
int &vlocal = v;
{
int v = 3; // within subscope
cout << "local: " << vlocal << endl;
}
}
但我会完全避免这种做法.我花了几个小时来调试这样的构造,因为在调试器中显示的变量因范围而改变,我无法弄清楚它是如何改变的.
这篇关于有没有办法在 C++ 中访问外部作用域中的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有没有办法在 C++ 中访问外部作用域中的局部变量?


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