如何访问另一个功能定义在一个函数声明的变量?(How to access variables def

2019-06-17 14:32发布

谁能告诉我如何访问声明和定义变量的函数在另一个函数。 例如

void function1()
{
   string abc;
}

void function2()
{
   I want to access abc here.
}

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

Answer 1:

C ++的方式是通过abc参照你的函数:

void function1()
{
    std::string abc;
    function2(abc);
}
void function2(std::string &passed)
{
    passed = "new string";
}

您还可以通过你的字符串作为指针,取消对它的引用在函数2。 这是更做事的C风格的方式,而不是安全的(例如,一个空指针可以传递,并且没有良好的错误检查会引起未定义的行为或崩溃。

void function1()
{
    std::string abc;
    function2(&abc);
}
void function2(std::string *passed)
{
    *passed = "new string";
}


Answer 2:

让全球那么这两个可以操纵它。

string abc;

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

void function2(){
    abc = "hello";
} 


Answer 3:

如果您有功能1要在功能2使用,则必须是一个变量:

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

如果你的函数2是从功能1叫,那么你可以把它作为一个参数传递给函数2。

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.";   
}   

如果功能1不调用函数2,但都被称为功能3,则有功能3声明变量,并传递到两个功能1和功能2作为参数。

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.";   
}    

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

std::string global_abc;  
void function1( )   
{   
   cout << global_abc << " is available everywhere.";   
}   
void function2( )   
{   
   cout << global_abc << " is available everywhere.";   
}    


Answer 4:

是绝对没有办法。 该块的变量只能从该块被直接访问。

指针/向对象的引用可以被传递到被从该块,作为参数调用的函数。



文章来源: How to access variables defined and declared in one function in another function?
标签: c++ scope