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

C++ accessing variable from other function

本文关键字:访问 变量 函数 其他 c++      更新时间:2023-10-16

我正在尝试用qt creator制作数字猜谜游戏。我需要从另一个函数访问一个变量。我可以通过在变量的开头添加"self."在python上做到这一点,但我不能在c++上做到这一点。下面是我正在尝试做的一个示例:

void function1()
{
   int i;
}
void function2()
{
   I need to access i here.
}

可以使用指针、类或全局变量(我建议使用指针或类)

void f1(int *iPtr)
{
    cout << "value= " <<*iPtr << endl;
}
void f2(int *iPtr)
{
   *iPtr = *iPtr + 5; // access ( modify ) variable here
    cout << "after addition = " << *iPtr << endl;
}
int main()
{
    int i = 5;
    int *iPtr;
    iPtr = &i; // point pointer to location of i
    f1(iPtr);
    f2(iPtr);
// after f1() value of i == 5, after f2() value of i == 10
}

我相信在c++中类似的行为应该是成员变量。

如果你还没有,我建议你使用类。因此,在你的头文件中像这样定义它:

class MyClass {
  public:
    void function1();
    void function2();
  private:
    int i;
};

如果你不使用c++类,那么你可以在头文件中定义"i",但这将使它在本质上是全局的。这可能不是最好的做法。

不可能从另一个函数访问变量,因为它们只存在于堆栈中,并且在函数退出时销毁。使用全局变量

您可以将i声明为全局变量,并在选择后为其分配随机数。这样,你仍然可以生成一个随机数,并在另一个函数中使用它。

int i;
void function1()
{
   int randNum;
    // get random number here
   i = randNum;
}
void function2()
{
   // do stuff with i here
}