函数传值

函数传值一共有三种类型:传对象,传地址,传引用

基础

形参:函数本身的参数,用来在函数内运算的参数
实参:用来给形参传递参数的值

int Max(int a,int b ){ //比较并返回大数};a,b都是形参
调用的时候int n=Max(10,15);10与15是实参;

传对象

把实参的值复制一份给形参,形参的运算跟实参无关。

#include <iostream>
#include <string>
using namespace std;
void swap(string,string);
void main(){
    string str1("now"),str("future");
    swap(str1,str2);
    cout<<"返回后:str1="<<str1<<"str2="<<str2<<endl;
}
void swap(string s1,string s2)
{
    string temp=s1;s1=s2;s2=temp;
    cout<<"交换为:str1="<<s1<<"str2="<<s2<<endl;
}

输出:
交换为:str1=future str2=now
返回后:str1=now str2=future

传指针

把实参原件传给形参,形参的变化就是对实参的改变。

#include <iostream>
#include <string>
using namespace std;
void swap(string*,string*);
void main(){
    string str1("now"),str("future");
    swap(str1,str2);
    cout<<"返回后:str1="<<str1<<"str2="<<str2<<endl;
}
void swap(string *s1,string *s2)
{
    string temp=*s1;*s1=*s2;*s2=temp;
    cout<<"交换为:str1="<<*s1<<"str2="<<*s2<<endl;
}

输出:
交换为:str1=future str2=now
返回后:str1=future str2=now

传引用

把实参的地址传给形参,如果形参变化的话,指向这个地址的实参也会变化。

#include <iostream>
#include <string>
using namespace std;
void swap(string&,string&);
void main(){
    string str1("now"),str("future");
    swap(str1,str2);
    cout<<"返回后:str1="<<str1<<"str2="<<str2<<endl;
}
void swap(string &s1,string &s2)
{
    string temp=s1;s1=s2;s2=temp;
    cout<<"交换为:str1="<<s1<<"str2="<<s2<<endl;
}

输出:
交换为:str1=future str2=now
返回后:str1=future str2=now

总结

对比学习确实能引发很多思考,但是还得在实践中不断成长。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 16
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值