值传递函数内部生成相应地址放置传入的值,相当于函数内部创建临时变量(隐形),所以不改变传入参数本来的值,
引用和指针传递都是对所在地址上的值更改,会改变传入得值
1 #include<iostream> 2 using namespace std; 3 //值传递 4 void sum(int a,int b) 5 { 6 a += 1; 7 b += 1; 8 } 9 //引用传递 10 void sum2(int &a,int &b) 11 { 12 a += 1; 13 b += 1; 14 } 15 //指针传递 16 void sum3(int *a,int *b) 17 { 18 *a += 1; 19 *b += 1; 20 } 21 //默认参数 22 void sum4(int a = 4, int b = 5) 23 { 24 cout<<"a+b= "<<a+b<<endl; 25 } 26 int main() 27 { 28 int a = 1, b = 3; 29 cout<<"before sum: a= "<<a<<" b= "<<b<<endl; 30 //值传递 31 sum(a,b); 32 cout<<"after sum: a= "<<a<<" b= "<<b<<endl; 33 a = 1, b = 3; 34 cout<<"before sum2: a= "<<a<<" b= "<<b<<endl; 35 //引用传递 36 sum2(a,b); 37 cout<<"after sum2: a= "<<a<<" b= "<<b<<endl; 38 //指针传递 39 a = 1, b = 3; 40 sum3(&a,&b); 41 cout<<"after sum3: a= "<<a<<" b= "<<b<<endl; 42 //默认参数 43 sum4(); 44 cin.get(); 45 return 0; 46 }
结果: