標籤:out exchange color str1 back div ffffff hang names
函數傳值
例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和p211 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把地址給了p318 p1=p2;//p2把地址給了p119 p2=p3;//p3把地址給了p220 //結果是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和p211 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的值 賦給 p318 *p1=*p2; //把p2指的str2的值 賦給 p119 *p2=p3; //把p3的值 賦給 p2指的str220 }
例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 }
C++