yesterday go to hospital...today go on...
the title "C++ ---- 指针和引用" only see something about "指针"...
today i use three simple example to explain it...
first...
Code:
void main()
{
int x=3,y=4,temp;
temp=x;
x=y;
y=temp;
}
then you can see x=4,y=3;
then let's if you use function to do this handle
1. 传值调用
void main()
{
int x=3,y=4;
swap(x,y);
}
void swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
then you can see although you use function swap try to swap the value of x and y...
but you can see they have not change the value...
why?
if you follow the code ,you can see the value of x and y which define in function swap changed in function swap,but the x,y which define in function main have not change...this is only "传值引用", the function swap only can use the value of x,y but can't change them...
maybe you can see no...because the value of x,y have changed inside swap...why do you say them can't change..
pay attention ...
the x,y in function swap do not equal to the x,y in main....
if you can understand this ,then the all is so easy...
you can try to change the Code to this:
void main()
{
int x=3,y=4;
swap(x,y);
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
do you understand? i think you can...because i have explain it so detailed...
2. 传址调用(用指针)
void main()
{
int x=3,y=4;
swap(&x,&y);
}
void swap(int *x,int *y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
also, for easy to understand, change the code to this:
void main()
{
int x=3,y=4;
swap(&x,&y);
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
the most important code is: *a=*b
it express that change the address of a and b...
this afternoon is so busy...so i can't complete it today...tomorrow...or next Monday continue...