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

时间:2013-09-10 03:30:56

标签: 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传递对函数的引用不适合我的情况,因为这会破坏调用函数的顺序。声明全局变量也被拒绝。

4 个答案:

答案 0 :(得分:5)

在C ++中,无法访问该函数范围之外的本地声明的函数变量。简单地说,你在这里要求的是什么:

  

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

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

您可以做的是将“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. 没有参数引用传递给相关方法。

答案 1 :(得分:1)

听起来你想从f2以外的其他地方拨打f1,例如

void foo() { f1(); f2(); }

如果是这种情况:调用f2时这些变量甚至不存在,因此无法访问。
(而且你误认为范围 生命周期。那些是非常不同的东西。)

可以做的一件事就是通过引用将变量传递给所有需要它们的函数。

void f1(double& a, int& b);
void f2(double& a, int& b);

void foo()
{
    double x;
    int y;
    f1(x, y);
    f2(x, y);
}

答案 2 :(得分:0)

你能做的事情与大狼建议的类似。您可以在函数内使用类声明。这有以下目的: 您可以定义仅在当前范围内可用的函数,因此无法在该范围之外访问该函数,并且该函数可以访问该范围内的变量,就好像它们是全局变量一样。该类也仅在您当前的范围内定义。

void    MyVeryComplicatedFunction
{
    int A;
    class localvars
    {
    public:
        int *ARef;              // this serves as the "Global" variables
        std::vector<int>    B;  // this serves as the "Global" variables

        localvars(int *inA) ARef(inA);

        void RepetativeOperation(int C) {
            (*ARef) += C;
            B.push_back(C);
        }
    }localvars(A);

    localvars.B.push_back(4);
    A = 3;
    localvars.RepetativeOperation(2);
    localvars.RepetativeOperation(4);
    localvars.RepetativeOperation(8);

    printf("A = %d, B[3] = %d", A, localvars.B[3]);
}

答案 3 :(得分:0)

#include<iostream>
using namespace std;
class c1 {
    string a;
    string b;

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

void c1::f1() {
    cin >> a;
    cin >> b;
    f2();
}

void c1::f2() {
    cout << "vals are: " << a << b;
}
相关问题