在参数传递时,被传递到函数的可以变量的值、地址、引用
一、传值
参数以 值 的方式传递。
#include<iostream>using namespace std;void changeAge(int age,int newAge);int main()
{int age=24;cout<<"My age is "<<age<<"\n"; //24changeAge(age,age+1); //以地址的方式传递参数 cout<<"Now my age is "<<age<<"\n"; //24return 0;
}void changeAge(int age,int newAge)
{age=newAge;cout<<"In this,my age is "<<age<<"\n"; //25
}
二、传址
参数以地址的方式传递,函数参数这里可以用指针(指针里存放的是地址)。
想要获取某个变量的地址,只能需要再变量面前加一个“取地址(&)”操作符就行了。
注意:如果传过去的是 地址,在函数中必须要通过“ *” 对指针进行解引用,除非你有其他用途。
案例1:
#include<iostream>using namespace std;void changeAge(int *age,int newAge);int main()
{int age=24;cout<<"My age is "<<age<<"\n"; //24changeAge(&age,age+1); //以地址的方式传递参数 cout<<"Now my age is "<<age<<"\n"; //25return 0;
}void changeAge(int *age,int newAge)
{*age=newAge;cout<<"In this,my age is "<<*age<<"\n"; //25
}
案例2:实现数值的调换
#include <iostream>using namespace std;void swap(int *x ,int *y);int main()
{int x,y;cout<<"请输入另个不同的值:";cin>>x>>y;swap(&x,&y);//参数以地址的方式传递
// cout<<"调换后输出:"<< x <<''<< y <<''<< "\n\n"; //报错 cout<<"调换后输出:"<< x <<' '<< y <<' '<< "\n\n"; //'' 中间记得加空格 return 0;
}void swap(int *x ,int *y)
{int temp;temp=*x;*x=*y;*y=temp;
}
三、传引用
参数以引用传递方式传递:使用某种约定使得在调用该函数时不需要使用指针的语法。
他跟我们传址的目的是一样的,都是把地址传递给函数,但语法不同更加容易使用了。
#include <iostream>using namespace std;void swap(int &x ,int &y);int main()
{int x,y;cout<<"请输入另个不同的值:";cin>>x>>y;swap(x,y);//这里编译器会自动把传过来的整型变量翻译成地址,而不是以变量的形式传递过去
// cout<<"调换后输出:"<< x <<''<< y <<''<< "\n\n"; //报错 cout<<"调换后输出:"<< x <<' '<< y <<' '<< "\n\n"; //'' 中间记得加空格 return 0;
}void swap(int &x ,int &y)
{int temp;temp=x;x=y;y=temp;
}
四、反汇编对比三种传递方式分析讲解运行原理
未完待续。。。