为什么这里的输出是30?以及fun()= 30的有效程度如何?给函数赋值是什么意思?为何删除静态关键字会引发细分错误?
#include<iostream>
using namespace std;
int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
答案 0 :(得分:2)
main()
fun()
内部。fun()
有一个静态变量x
(静态意味着x
存储在内存的特定部分中而不是堆栈中,因此在函数调用之间保留其值) (这就像有一个全局变量,仅在fun()
内部可见)fun()
返回对x
的引用(引用几乎类似于指针)x
的返回的 reference ,因此x
实际上被更改了! (您不要写函数)x
是30,而fun()
在下一次通话时返回30。我希望这能回答您的前三个问题。
在这种情况下,堆栈上确实存在x
。因此,每当您调用fun()
时,就会在堆栈上分配一些内存来保存x
。当fun()
返回时,该内存将被释放。
现在,fun()
返回的引用将引用一块内存,该内存不再由您的程序分配。换句话说,返回的引用将引用一个内存地址,该地址“不属于您的程序”,因此不允许您对其进行写入。因此您会遇到细分错误。
要回答您问题的实际标题:是的,我们可以使用函数指针:
int foo(int x) {
return x + 1;
}
int bar(int x) {
return x * 2;
}
void main() {
int(*f)(int) = foo;
// int the function pointed to returns an int
// (*f) f is the name of the function pointer
// (int) the function pointed to takes on int as paramter
// = foo; f now points to the function foo()
(*f)(3); // the same as foo(3), returns 4
f = bar; // now f points to bar()
(*f)(3); // the same as bar(3), returns 6
}
答案 1 :(得分:0)
fun()
返回对静态变量x
的引用,并为其分配值30
。您无需为函数本身分配任何内容。实际上,不可能为C ++中的函数分配任何内容。