函数传值
函数传值
例1:
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 int main(){ 5 string str1="I love China!",str2="I love JiNan!"; 6 void Exchange(string *p1,string *p2); 7 cout<<"str1: "<<str1<<endl; 8 cout<<"str2: "<<str2<<endl; 9 Exchange(&str1,&str2); 10 //取str1和str2的地址交给p1和p2 11 cout<<"str1: "<<str1<<endl; 12 cout<<"str2: "<<str2<<endl; 13 return 0; 14 } 15 void Exchange(string *p1,string *p2){ 16 string *p3; 17 p3=p1;//p1把地址给了p3 18 p1=p2;//p2把地址给了p1 19 p2=p3;//p3把地址给了p2 20 //结果是p1/p2/p3相互换地址,并没有影响str1/str2的值 21 }
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 int main(){ 5 string str1="I love China!",str2="I love JiNan!"; 6 void Exchange(string *p1,string *p2); 7 cout<<"str1: "<<str1<<endl; 8 cout<<"str2: "<<str2<<endl; 9 Exchange(&str1,&str2); 10 //取str1和str2的地址交给p1和p2 11 cout<<"str1: "<<str1<<endl; 12 cout<<"str2: "<<str2<<endl; 13 return 0; 14 } 15 void Exchange(string *p1,string *p2){ 16 string p3; 17 p3=*p1; //把p1指的str1的值 赋给 p3 18 *p1=*p2; //把p2指的str2的值 赋给 p1 19 *p2=p3; //把p3的值 赋给 p2指的str2 20 }
例2:
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 5 //输出p=2 6 void function(int p1) 7 { 8 p1=5; 9 } 10 11 int main() 12 { 13 int p=2; 14 function(p); 15 cout<<p<<endl; 16 return 0; 17 }
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 5 //输出p=5 6 void function(int *p1) 7 { 8 *p1=5; 9 } 10 11 int main() 12 { 13 int p=2; 14 function(&p); 15 cout<<p<<endl; 16 return 0; 17 }