为什么这里的输出是30?fun()=30 如何有效?给函数赋值是什么意思?为什么删除静态关键字会引发分段错误?
#include<iostream>
using namespace std;
int &fun()
{
static int x = 10;
return x;
}
int main()
{
fun() = 30;
cout << fun();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
main() fun()叫。fun()有一个静态变量x(静态意味着x存储在内存的特殊部分而不是堆栈上,因此它的值在函数调用之间保留)(就像有一个仅从内部可见的全局变量fun())fun()返回一个引用x(引用几乎就像指针)x因此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
}
Run Code Online (Sandbox Code Playgroud)