Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

scope - access variables from other function c++

I must access variables declared inside other function.

Assume f1()

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

and f2()

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

Is it possilbe in c++? How can that be done?

Passing reference to function as shown here is not suitable answer for my case because this corrupts the order of calling functions. Declaring global variables also denied.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In C++ there is no way to access locally declared function variables outside of that function's scope. Simply put, what you are asking for here:

I must access variables declared inside another function.

is simply impossible. Anything you try that seems to allow you to do that is undefined behavior.

What you can do is turn "f1" and "f2" as methods of a class and put double a and int b as member data states:

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
}

This fulfills your two requirements. Namely:

  1. No global variables are used.
  2. No parameter references are passed into the methods in question.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...