C++指针 传值 传址 传引用

来源:互联网 发布:七牛云存储源码 编辑:程序博客网 时间:2024/06/05 22:30

转自http://blog.chinaunix.net/uid-11775320-id-2830460.html

写的挺不错的

#include "stdafx.h"
#include "iostream"
using namespace std;//我是在VS2008里面作的调试,这里需要导入命名空间STD

void swap1(int x,int y)//传值调用

{
    //实际上在传值调用时,是把数据的副本传给了被调用函数,

    //被调用函数内是交换了的,而主函数里面保持原值

    int temp;
    temp = x;
    x = y;
    y = temp;
    cout<<" 传值函数内: "<<x<<" "<<y<<endl;
}
void swap2(int *x,int *y) //传址调用

{
    //把主函数里数据的地址传了过来

    //这里改变了数据的地址,在主函数里打印出a,b的时候,当然就发生了交换!

    int temp;
    temp = *x;
    *= *y;
    *= temp;
    cout<<" 传址函数内: "<<x<<" "<<y<<endl;

注意要是修改x和y的内容需要用temp=*x; 直接定义int *temp;temp=x;这样xy和temp就一样了,跟本交换不了

int i=10;
int *i0=&i;
int *i1=new int ;
*i1=*i0;
*i0=11;

改变i0后,i1同时会变成11而不是10


}
void swap3(int &x,int &y)//传引用

{
    //加了&之后,用地址引用了主函数里面的数据值,说明x,y 的地址是a,b的地址~~,因而主函数里面的a,b发生交换~~

    int temp;
    temp = x;
    x = y;
    y = temp;
    cout<<" 换址函数内: "<<x<<" "<<y<<endl;
}

void main()//入口点

{
    int a(8);
    int b(3);

    cout<<" 数据: "<<"a"<<" "<<"b"<<endl;
    cout<<" 初值: "<<a<<" "<<b<<endl;
    //传值调用

    swap1(a,b);
    cout<<" 传值调用: "<<a<<" "<<b<<endl;
    //传址调用

    swap2(&a,&b);
    cout<<" 传址调用: "<<a<<" "<<b<<endl;
    //恢复原值

    swap2(&a,&b);
    //传引用调用

    swap3(a,b);
    cout<<" 引用调用: "<<a<<" "<<b<<endl;
    getchar();
}


output: