1传值
1 int test(int x)
2 {
3 x = x + 1;
4 cout << x << endl;
5 cout << &x << endl;
6 return x; 7 } 8 9 int main() 10 { 11 int a = 3; 12 test(a); 13 cout << a<< endl; 14 cout << &a <<endl; 15 return 0; 16 }
运行结果
4
000000EB483BFA70
3
000000EB483BFA94
即:调用函数在栈中分配给形参储存单元 ,并赋值,形参的运算与实参无关
2传址
1 int test(int *x)
2 {
3 *x = *x + 1;
4 cout << *x << endl;
5 cout << &x << endl;
6 return *x; 7 } 8 9 int main() 10 { 11 int a = 3; 12 test(&a); 13 cout << a<< endl; 14 cout << &a <<endl; 15 return 0; 16 }
运行结果
4
0000002BF814F980
4
0000002BF814F9A4
即:调用函数在栈中分配给指向实参的指针,对指针指向的单元进行运算,会改变实参取值
3传引用
1 int test(int &x)
2 {
3 x = x + 1;
4 cout << x << endl;
5 cout << &x << endl;
6 return x; 7 } 8 9 int main() 10 { 11 int a = 3; 12 test(a); 13 cout << a<< endl; 14 cout << &a <<endl; 15 return 0; 16 }
运行结果
4
000000D1FF94F964
4
000000D1FF94F964
即:在调用函数中引用了实参a,x相当于实参a的另一个标号,没有在栈中分配内存,对形参x操作相当于对实参a操作,并节约了栈的操作
2020.4.4