我必须访问在其他函数内声明的变量。
假设 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 a
和int 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
}
这满足了您的两个要求。即:
- 没有使用全局变量。
- 没有参数引用被传递到有问题的方法中。
关于c++ - 从其他函数访问变量 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18710282/