static在第二次调用时能保持第一次用完后的值。
#include <iostream>
using namespace std;
int f(int n);
int main()
{
cout<<f(5)<<" ";//此行执行完后,a的值为7,b的值为0
cout<<f(8)<<endl;//此行执行时,a保持不变,仍为7,在执行完a+=n之后,a变为15,所以b+=a之后b也是15.
return 0;
}
int f(int n)
{
static int a=2;
int b=0;
a+=n;
b+=a;
return b;
}
执行结果