函数传值一共有三种类型:传对象,传地址,传引用
基础
形参:函数本身的参数,用来在函数内运算的参数
实参:用来给形参传递参数的值
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
总结
对比学习确实能引发很多思考,但是还得在实践中不断成长。