C++入门经典-例5.7-调用自定义函数交换两变量值,传入指针

1:代码如下:

// 5.7.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;
void swap(int *a,int *b)
{
    int tmp;
    tmp=*a;
    *a=*b;
    *b=tmp;
}
void swap(int a,int b)
    {
    int tmp;
    tmp=a;
    a=b;
    b=tmp;
}
void main()
{
    int x,y;
    int *p_x,*p_y;
    cout << " input two number " << endl;
    cin >> x;
    cin >> y;
    p_x=&x;p_y=&y;
    cout<<"按指针传递参数交换"<<endl;
    swap(p_x,p_y);//执行的是参数列表都为指针的swap函数
    cout << "x=" << x <<endl;
    cout << "y=" << y <<endl;
    cout<<"按值传递参数交换"<<endl;
    swap(x,y);
    cout << "x=" << x <<endl;
    cout << "y=" << y <<endl;
}
View Code

运行结果:

C++入门经典-例5.7-调用自定义函数交换两变量值,传入指针