如何在 C++ 的外部函数中使用变量?

How can I use variable in external function in c++?

我在主函数中得到了一个输入变量。我想在外部函数 2 中使用这个变量,它已经被函数 1 再次调用为外部函数(如下面的代码)。但是这个变量在 function2 处是未定义的。请帮我。感谢所有答案。这是我的代码的概述:

int main ()
{
int boogh;
cin >> boogh;
function1 (x,y);
}

function1(int x,int y)
{.
 .
function2(w,z);
 .
 .
}

function2(int w, int z)
{
if (boogh>5)
    {.
     do some thing
     .
     .
    } 
}

函数1和函数2是递归的

您必须通过值或引用将所需变量传递给函数:

为您的案例传递价值:

// Example program
#include <iostream>
#include <string>

using namespace std;

void function1(int x);
void function2(int x);

int main ()
{
    int boogh;
    cin>>boogh;
    function1 (boogh);
}

void function1(int x)
{
    function2(x);
}

void function2(int y)
{
    int boogh=y;
    if (boogh>5)
    {
        //do something here
    } 
}

该变量在 main 范围内,因此您无法在那里访问它。您需要将它(或它的副本)放入 function2 的范围内。一种方法是将它作为函数参数传递给两个函数,因为它必须经过 function1 才能到达 function2:

void function1(int x, int y, int boogh) {
    //...
    function2(w, z, boogh);
    //...
}

void function2(int w, int z, int boogh) {
    if (boogh > 5) {  // the value is available here
        //...
    }
}

int main() {
    int boogh;
    cin >> boogh;
    function1(x,y,boogh);
}

或者您可以将变量和使用它的函数封装在 class:

struct thingy {
    int boogh;
    void function1(int x,int y) {
        //...
        function2(w, z);
        //...
    }
    void function2(int w,int z) {
        if (boogh > 5) { // class member accessible here
            //...
        }
    }
};

int main() {
    thingy t;
    cin >> t.boogh;
    t.function1(x,y);
}

或者您可以使用全局变量,但这几乎总是一个坏主意。