注册 登录
编程论坛 C++教室

函数参数的三种传递方法

hmsabc 发布于 2010-09-26 22:38, 557 次点击
//1. 将变量名作为实参和形参--函数参数传递方法之一
/*
#include<iostream.h>
//using namespace std;

int main()
{
    void swap(int,int);             //申明函数 swap
    int i=3,j=5;
    swap(i,j);                      //调用函数
    cout << i << " " << j << endl;  //输出 i 和 j 的值
    return 0;
}

void swap(int a,int b)        //定义函数,
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}
*/

//这种方式, swap 函数意欲通过传递变量参数,使变量 i 和 j 的值互换, 事实证明不能实现

//2. 传递变量的指针--函数参数传递方法之二
/*
#include <iostream.h>

int main()
{
    void swap( int *, int *);
    int i=3,j=5;
    swap(&i,&j);
    cout << i << " " << j << endl;
    return 0;
}

void swap(int * p1,int * p2)
{
    int temp;
    temp = *p1;
    *p1 = *p2;
    *p2 = temp;
}
*/

//这种方式,仍然属于“值传递”,只是实参的值是变量的地址而已。通过形参指针变量访问主函数
//中的变量(i 和 j),并改变他们的值。 这样就得到了正确结果,但是在概念上却兜了一个圈子。

//3.传递变量的别名--函数参数传递方法之三

#include <iostream.h>

int main()
{
    void swap( int &, int &);
    int i=3,j=5;
    swap(i,j);
    cout << i << " " << j << endl;
    return 0;
}

void swap(int &a,int &b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}
//C语言中无传递变量别名的方法,C++把引用型作为函数形参,弥补了C语言的不足。
2 回复
#2
DestinyLord2010-09-29 15:19
支持一下~~
#3
小葳的宝宝2010-10-02 20:52
虽然我还不能完全看懂。。。但还是弱弱地顶一下!
1