从其他函数访问变量c ++

Nur*_*lan 0 c++ scope global-variables local

我必须访问在其他函数中声明的变量。

假设 f1()

void f1()
{
  double a;
  int b;
  //some operations
}
Run Code Online (Sandbox Code Playgroud)

f2()

void f2()
{
  //some operations
  //access a and b from f1()
}
Run Code Online (Sandbox Code Playgroud)

在C ++中是possilbe吗?那怎么办?

提到过如图所示的功能这里不是我的情况适合的答案,因为这会破坏调用函数的顺序。声明全局变量也被拒绝。

gre*_*olf 5

在C ++中,无法访问超出该函数范围的本地声明的函数变量。简而言之,您在这里的要求是什么:

我必须访问在另一个函数中声明的变量。

根本不可能。任何你尝试似乎允许你这样做是不确定的行为。

您可以做的是将“ f1”和“ f2”设置为类的方法,并将put double aint bmember数据状态设置为:

class c1
{
  double a;
  int b;

public:
  void f1();
  void f2();
};

void c1::f1()
{
  // f1 can access a and b.
  //some operations
}

void c1::f2()
{
  // f2 can see the changes made to a and b by f1
}
Run Code Online (Sandbox Code Playgroud)

这满足您的两个要求。即:

  1. 没有使用全局变量。
  2. 没有参数引用传递到所讨论的方法中。