C++ ---- 指针和引用(续)

 

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...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值