函数参数的传递
值传递
变量为实参,将实参的值拷贝一份传递到函数中,具有各自的内存空间,函数对形参的修改不会影响实参
void swap1(int x,int y){
int temp;
temp=x;
x=y;
y=temp;
}
引用传递
引用
数据类型 &变量别名=变量名
为变量起一个别名,二者共用内存空间
但若不是作为函数参数或者返回值,需要提供初值
int a;
int &b=a;
引用传递
实参为变量,引用变量作为函数的形参,对形参的操作即是对实参的操作
//交换两个变量的值
#include <iostream>
using namespace std;
void swap1(int &x,int &y){
int temp;
temp=x;
x=y;
y=temp;
}
int main(){
cout<<"输入两个数"<<endl;
int a,b;
cin>>a>>b;
swap1(a,b);
cout<<a<<' '<<b;
return 0;
}
地址传递
实参为变量的地址,形参为指针变量,函数通过变量的地址对实参变量进行间接访问,达到引用传递的类似作用
#include <iostream>
using namespace std;
void swap(int *x,int *y){
int temp;
temp=*x;
*x=*y;
*y=temp;
}
int main(){
cout<<"输入两个数"<<endl;
int a,b;
cin>>a>>b;
swap(&a,&b);
cout<<a<<' '<<b;
return 0;
}
数组与结构体做参数
类似指针地址传递,函数操作直接对实参变量进行操作
一维数组
int f(int p[]);
int k[maxsize];
f(k);
二维数组:形参的列不能省略
int f(int p[][10]);
int k[20][10];
f(k);
结构体直接作为函数形参为值传递
引用传递与地址传递
二者的本质实质上都是共用内存地址,只是方式不同
int k;
int p0=&k; //p0是变量名
int *p1,*p2;
p1=&k; //p1,p2是指针
p2=p1;
修改p0,p1,p2任意一个的值,都会改变k的值,同时改变这四个变量的值
以person类为例
#include <iostream>
#include <string.h>
using namespace std;
class person{
private:
int age;
char name[10];
char sex;
public:
person(){
strcpy(name,"xxx");
age=0;
sex=' ';
}
~person(){}
void Register(char *name,int age,char sex);
void showme();
};
void person::Register(char *name,int age,char sex){
strcpy(this->name,name);
this->age=age;
this->sex=sex;
}
void person::showme(){
cout<<this->name<<'\t'<<this->age<<'\t'<<this->sex<<endl;
}
int main(){
person *p1,*p2;
p1=new person;
cout<<"person 1:\t";
p1->showme();
p1->Register("zhangsan",19,'m');
cout<<"person1:\t";
p1->showme();
p2=p1;
person &p3=*p1;
cout<<"person 3:\t";
p3.Register("lisi",19,'m');
p3.showme();
cout<<"person2:\t";
p2->showme();
cout<<"person 1:\t";
p1->showme();
cout<<"person 3:\t";
p3.showme();
delete p1;
system("pause");
return 0;
}