1 void test(int x)
2 {
3 x = 1024;
4 cout << "test函数里x的值为" << x << endl;
5 }
6
7 int main()
8 {
9 int x = 1;
10 cout << "test函数开始前x的值为"<< x << endl;
11 test(x);
12 cout << "test函数开始后x的值为"<< x << endl;
13
14 return 1;
15 }
上述代码的结果为 1, 1024, 1,说明在test函数里面,新开辟了一个局部变量x的空间,在main中并没有把x改回来,代码安全性较低。
void test(int &x)
{
x = 1024;
cout << "test函数里x的值为" << x << endl;
}
int main()
{
int x = 1;
cout << "test函数开始前x的值为"<< x << endl;
test(x);
cout << "test函数开始后x的值为"<< x << endl;
return 1;
}
加了引用之后,输出结果为1, 1024, 1024,这里的x的空间只有一份,节约了空间也提高了代码的安全性。
除此之外,如果在引用前加const,则是告诉使用者使用这个函数不会改变你的参数。



