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++ 中访问外部作用域中的局部变量?
基础教程推荐
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
