访问调用函数的局部变量

Access calling function's local variable

本文关键字:局部变量 函数 调用 访问      更新时间:2023-10-16

这是该问题的一个玩具示例。我有一个大的父函数,除其他外,它调用两个子函数。实际上,这个父函数位于用于其他事情的基类上,所以我不想重写父函数或包装的函数以通过引用传递变量,因为继承基的其他子类不需要它们。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> .