天天看點

C++傳值,傳引用,傳位址的差別

#include <iostream>
using namespace std;

void swap0(int a,int b)
{
    int temp;
    temp=a;
    a=b;
    b=temp;
}

void swap1(int &a,int &b)
{
    int temp;
    temp=a;
    a=b;
    b=temp;
}

void swap2(int *a ,int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}

int main()
{
    int s1,s2;
    s1=111;
    s2=222;
    swap0(s1,s2);
    cout<<"swap0結果:";
    cout<<s1<<" ";
    cout<<s2<<endl;

    s1=111;
    s2=222;
    swap1(s1,s2);   //注意用法
    cout<<"swap1結果:";
    cout<<s1<<" ";
    cout<<s2<<endl;

    s1=111;
    s2=222;
    swap2(&s1,&s2);
    cout<<"swap2結果:";
    cout<<s1<<" ";
    cout<<s2<<endl;

    return 0;
}
swap0結果:111 222
swap1結果:222 111
swap2結果:222 111