码迷,mamicode.com
首页 > 编程语言 > 详细

C++

时间:2017-10-24 14:11:49      阅读:159      评论:0      收藏:0      [点我收藏+]

标签: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和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 }

 

C++

标签:out   exchange   color   str1   back   div   ffffff   hang   names   

原文地址:http://www.cnblogs.com/xumh/p/7722976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!