从其他函数c ++访问变量 [英] access variables from other function c++

查看:166
本文介绍了从其他函数c ++访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



假设 f1()

  void f1()
{
double a;
int b;
//一些操作
}

f2 ()

  void f2()
{
//一些操作
//从f1访问a和b()
}

possilbe在C ++?如何做到这一点?



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

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


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


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



你可以做的是将f1和f2作为类的方法,并将 double a int b 作为成员数据状态:

  class c1 
{
double a;
int b;

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

void c1 :: f1()
{
// f1可以访问a和b。
//一些操作
}

void c1 :: f2()
{
// f2可以看到a和b所做的更改f1
}

这符合您的两项要求。即:


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


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.

解决方案

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.

这篇关于从其他函数c ++访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆