10行经典代码,两种结果,阐述static的作用。废话少说,直接码字。【看懂了,点个赞哈】
// 包含static静态局部变量i的结果,静态局部变量i都保存了前次test函数被调用后留下来的值。
#include <iostream>
using namespace std;
void test() {
static int i = 10;cout << i<<endl;
i++;
}
void main() {
test();
test();
test();
system("pause");
}
运行结果: 10 11 12
// 不包含static静态局部变量的结果
#include <iostream>
using namespace std;
void test() {
int i = 10;cout << i<<endl;
i++;
}
void main() {
test();
test();
test();
system("pause");
}
运行结果: 10 10 10
【举个例子:用static,编写3的立方小程序】
#include<iostream>
using namespace std;
int mul(int x)
{
static int n = 1;
n = n*x;
return n;
}
void main()
{
int i = 3;
int iResult;
for (int j = 1; j<4; j++)
{
iResult = mul(i);
}
cout << "Result :" << iResult << endl;
system("pause");
}
using namespace std;
int mul(int x)
{
static int n = 1;
n = n*x;
return n;
}
void main()
{
int i = 3;
int iResult;
for (int j = 1; j<4; j++)
{
iResult = mul(i);
}
cout << "Result :" << iResult << endl;
system("pause");
}