函数的值传递和指针传递的区别

 1 #include <iostream>
 2 using namespace std;
 3 
 4 //函数的值传递
 5 template<typename T>
 6 void swapValue(T a, T b){
 7     cout<<"值传递函数开始前a = "<<a<<", "<<"b = "<<b<<endl;
 8     T temp;
 9     temp = a;
10     a = b;
11     b = temp;
12     cout << "值传递函数结束在函数内部打印a = "
13     <<a<<", "<<"b = "<<b<<endl;
14 }
15 
16 //函数的指针传递
17 template<typename T>
18 void swapPoint(T *a, T *b){
19     cout<<"指针传递函数开始前a的地址为"<<a<<", b的地址为"<<b<<endl;
20     cout<<"指针传递函数开始前a的值为"<<*a<<", b的值为"<<*b<<endl;
21     T temp = *a;
22     *a = *b;
23     *b = temp;
24     cout<<"指针传递函数开始后函数内打印a的地址为"
25     <<a<<", b的地址为"<<b<<endl;
26     cout<<"指针传递函数开始后函数内打印a的值为"
27     <<*a<<", b的值为"<<*b<<endl;
28 }
29 
30 int main() {
31     int a = 4;
32     int b = 2;
33     swapValue<int>(a, b);
34     cout << "swapValue函数结束后打印a = "
35          <<a<<", "<<"b = "<<b<<endl;
36     swapPoint<int>(&a, &b);
37     cout<<"swapPoint函数结束后打印a的地址为"
38         <<a<<", b的地址为"<<b<<endl;
39     cout<<"swapPoint函数开结束后打印a的值为"
40         <<&a<<", b的值为"<<&b<<endl;
41     return 0;
42 }

打印输出结果:

函数的值传递和指针传递的区别

 

函数的值传递和指针传递的区别

上一篇:ERROR: Cannot load message class for


下一篇:错位储存