访问调用函数的局部变量
Access calling function's local variable
这是该问题的一个玩具示例。我有一个大的父函数,除其他外,它调用两个子函数。实际上,这个父函数位于用于其他事情的基类上,所以我不想重写父函数或包装的函数以通过引用传递变量,因为继承基的其他子类不需要它们。parentFunc 也在多个线程上被调用,所以我不能只是将 needThisInSecondWrappedFunc 变量作为类级变量,因为它会在线程之间错误地共享。
在我看来,在父函数上制作局部变量对两个子函数可见,然后可以对 parentFunc 的局部变量进行操作,但事实并非如此。
#include <iostream>
void parentFunc(float& data);
void wrappedFunc(float& ref);
void secondWrappedFunc(float& ref);
void parentFunc(float& data)
{
float needThisInSecondWrappedFunc[3];
wrappedFunc(data);
secondWrappedFunc(data);
}
void wrappedFunc(float& ref)
{
needThisInSecondWrappedFunc[0] = ref * 0.5f;
needThisInSecondWrappedFunc[1] = ref * 0.5f;
needThisInSecondWrappedFunc[2] = ref * 0.5f;
}
void secondWrappedFunc(float& ref)
{
ref = needThisInSecondWrappedFunc[0] +
needThisInSecondWrappedFunc[1] +
needThisInSecondWrappedFunc[3];
}
int main()
{
float g;
g = 1.0f;
parentFunc(g);
std::cout << g << 'n';
return 0;
}
我不确定为什么wrappedFunc和secondWrappedFunc看不到parentFunc的局部变量 - 我认为parentFunc局部变量此时仍在范围内?
C++中没有父函数访问的概念。
您只能访问全局范围("全局"变量),然后访问当前函数内的局部变量。如果您位于对象实例中,则还可以访问这些内容。
无法访问在另一个函数中声明的变量。
你需要做的是这样的:
void parentFunc(float& data);
void wrappedFunc(float& ref, float* needThisInSecondWrappedFunc);
void secondWrappedFunc(float& ref, const float* needThisInSecondWrappedFunc);
void parentFunc(float& data)
{
float needThisInSecondWrappedFunc[3];
wrappedFunc(data, needThisInSecondWrappedFunc);
secondWrappedFunc(data, needThisInSecondWrappedFunc);
}
void wrappedFunc(float& ref, float* needThisInSecondWrappedFunc)
{
needThisInSecondWrappedFunc[0] = ref * 0.5f;
needThisInSecondWrappedFunc[1] = ref * 0.5f;
needThisInSecondWrappedFunc[2] = ref * 0.5f;
}
void secondWrappedFunc(float& ref, const float* needThisInSecondWrappedFunc)
{
ref = needThisInSecondWrappedFunc[0] +
needThisInSecondWrappedFunc[1] +
needThisInSecondWrappedFunc[3];
}
或者更好的是,使用 std::array<float, 3>
.
相关文章:
- 局部变量保留函数中的值
- 如何使用 C++ 中的继承函数访问派生类中的局部变量
- 如何在函数外部访问函数中局部变量的值?
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- 获取具有静态局部变量的绑定/推断捕获 lambda 的函数指针
- 是否可以影响 C++ 中回调函数的局部变量?
- 将共享指针传递给函数参数 - 将其分配给局部变量的正确方法是什么
- 调用一个小函数两次(例如在if条件和主体中)比将结果存储在局部变量中更可取
- C++ - 指向函数中局部变量的指针
- 如何在 C++ 的 lambda 函数中传递同名的局部变量和参数(使用此关键字)?
- Clang++ 6.0 内存清理器未报告返回值指示条件分支的函数中的未初始化局部变量
- 如何将局部变量传递给 lambda 函数
- 局部变量的作用域是块或函数
- 函数原型未初始化的局部变量
- 尝试声明函数的局部变量,但得到范围错误
- 如果对象是通过 new 创建的,则成员函数的局部变量在哪里创建?
- 如果两个线程调用同一个函数,但函数中的所有变量都是局部变量,我还需要担心线程之间共享数据吗?
- 如果函数抛出的异常可能未捕获,如何销毁局部变量?
- 为什么不能在模板函数中向局部变量添加低级 const 类型
- 使用clang_complete自动完成局部变量/函数