如何访问另一个函数中一个函数中定义和声明的变量?

Var*_*tre 13 c++ scope

任何人都可以告诉我如何访问另一个函数中的函数声明和定义的变量.例如

void function1()
{
   string abc;
}

void function2()
{
   I want to access abc here.
}
Run Code Online (Sandbox Code Playgroud)

怎么做?我知道使用参数,我们可以做到这一点,但还有其他方法吗?

Joe*_*ish 15

C++的方式是abc通过引用传递给你的函数:

void function1()
{
    std::string abc;
    function2(abc);
}
void function2(std::string &passed)
{
    passed = "new string";
}
Run Code Online (Sandbox Code Playgroud)

您也可以将字符串作为指针传递,并在function2中取消引用它.这更像是C风格的处理方式而且不那么安全(例如,可以传入NULL指针,如果没有良好的错误检查,它将导致未定义的行为或崩溃.

void function1()
{
    std::string abc;
    function2(&abc);
}
void function2(std::string *passed)
{
    *passed = "new string";
}
Run Code Online (Sandbox Code Playgroud)


Ben*_*enN 8

让它全球化,然后两者都可以操纵它.

string abc;

void function1(){
    abc = "blah";
} 

void function2(){
    abc = "hello";
} 
Run Code Online (Sandbox Code Playgroud)

  • 如果他不熟悉变量范围,那么有可能他不知道这种方式是可能的. (3认同)

Sta*_*lot 5

如果你想在function2中使用function1中的变量,那么你必须:

  1. 直接传递,
  2. 有一个更高的范围函数,它调用声明变量并传递它,或者
  3. 将它声明为全局,然后所有函数都可以访问它

如果从function1调用function2,那么你可以将它作为参数传递给function2.

void function1()  
{  
    std::string abc;  
    function2( abc );  
}  

void function2( std::string &passed )   
{   
    // function1::abc is now aliased as passed and available for general usage.
   cout << passed << " is from function1.";   
}   
Run Code Online (Sandbox Code Playgroud)

如果function1没有调用function2,但是都被function3调用,那么让function3声明变量并将它作为参数传递给function1和function2.

void parentFunction( )
{
    std::string abc;  
    function1( abc );  
    function2( abc );  
}
void function1( std::string &passed )   
{   
   // Parent function's variable abc is now aliased as passed and available for general usage.
   cout << passed << " is from parent function.";   
}   
void function2( std::string &passed )   
{   
    // Parent function's variable abc is now aliased as passed and available for general usage.
   cout << passed << " is from parent function.";   
}    
Run Code Online (Sandbox Code Playgroud)

最后,如果既没有功能1也不函数2从相互调用,也没有从代码中的相同的功能,则声明为全局要共享的变量,功能1和功能2将能够直接使用它.

std::string global_abc;  
void function1( )   
{   
   cout << global_abc << " is available everywhere.";   
}   
void function2( )   
{   
   cout << global_abc << " is available everywhere.";   
}    
Run Code Online (Sandbox Code Playgroud)