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

标签 c++ scope global-variables local

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

假设 f1()

void f1()
{
  double a;
  int b;
  //some operations
}

f2()

void f2()
{
  //some operations
  //access a and b from f1()
}

在 C++ 中可以吗?怎么办?

传递对函数的引用,如图所示 here不适合我的情况,因为这会破坏调用函数的顺序。声明全局变量也被拒绝。

最佳答案

在 C++ 中,无法访问函数范围之外的局部声明函数变量。简而言之,您在这里要求的是:

I must access variables declared inside another function.

根本不可能。您尝试的任何似乎允许您这样做的行为都是未定义的行为。

你可以做的是将“f1”和“f2”作为一个类的方法,并将double aint b作为成员数据状态:

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
}

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

  1. 没有使用全局变量。
  2. 没有参数引用被传递到有问题的方法中。

关于c++ - 从其他函数访问变量 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18710282/

相关文章:

C++ 成员引用基类型 'int' 不是结构或 union

c++ - 关于继承的问题

java - 用Java重构这个函数

node.js - Node.js 中 process.emit 的事件范围

c - 8051 的 sdcc 编译器的奇怪行为

global-variables - 如何在序列图中通过全局变量表达交互

c - 共享 C 数组的最优雅方式

c++ - 在共享顶点上应用颜色

c++ - 在 std::map 中使用引用

c++ - 在 for 循环中声明 vector