任何人都可以告诉我如何访问另一个函数中声明和定义的函数中的变量。例如如何访问在另一个函数中的函数中定义和声明的变量?
void function1()
{
string abc;
}
void function2()
{
I want to access abc here.
}
如何做到这一点? 我知道使用参数我们可以做,但有没有其他方式?
任何人都可以告诉我如何访问另一个函数中声明和定义的函数中的变量。例如如何访问在另一个函数中的函数中定义和声明的变量?
void function1()
{
string abc;
}
void function2()
{
I want to access abc here.
}
如何做到这一点? 我知道使用参数我们可以做,但有没有其他方式?
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";
}
谢谢我会尽力让你知道:D – 2012-08-02 18:59:04
这工作! :D 谢谢! – 2012-08-03 07:27:48
绝对没有办法。块的变量只能从该块直接访问。
指向对象的指针/引用可以传递到从此块中调用的函数作为参数。
这是当然,错误。范围设定将对象的名称限制为在另一个块中可见。它不限制对象的访问。访问可以通过传递参考等方式获得。 – 2012-08-02 18:21:44
@EricPostpischil但引用什么?范围定义也定义了对象的生命周期,除非它是静态的或动态分配的。此外,OP指定了“无参数”。 – juanchopanza 2012-08-02 18:25:46
将参考放入全局变量中。将引用传递给其他函数。将引用传递给使其他函数可访问的函数。以指针作为参数,并将引用存储在指向的位置。等。 – 2012-08-02 18:30:06
如果在功能1要在函数2使用一个变量,那么你必须:。
如果你的函数2是从功能1叫,然后就可以只是将它作为参数传递给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.";
}
如果FUNCTION1没有调用函数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.";
}
我建议你阅读范围界定,你会明白为什么这是不可能的。 – 2012-08-02 18:19:50
这样做毫无意义:每次调用'function1'都有一个'abc'实例。在for(int i = 0; i <100; ++ i){function1(); }'你想要'abc'的一百个实例中的哪一个? – 2012-08-02 18:21:00
你知道静态成员吗? – phadaphunk 2012-08-02 18:29:25