引用和使用引用传递参数《二》
2012-09-17 21:08
302 查看
使用引用传递参数
在C++语言中,函数参数的传递只要有2种,分别为值传递和引用传递,所谓值传递,是指在函数调用时,将实际参数的值传递到调
用函数中,这样如果在调用函数中修改了参数的值,其不会改变到实际参数的值。二引用传递则相反,如果函数按引用方式传递,
在调用函数中修改了参数的值,其改变会影响到实际的参数。
经典的例子就是2个数交换。
先看一下值传递:
//其值不会交换。
再来看一下引用传递
当然你还可以用指针变量作为函数参数,效果和引用传递一样。
你还可以交换指针变量所保存的地址哦。
在C++语言中,函数参数的传递只要有2种,分别为值传递和引用传递,所谓值传递,是指在函数调用时,将实际参数的值传递到调
用函数中,这样如果在调用函数中修改了参数的值,其不会改变到实际参数的值。二引用传递则相反,如果函数按引用方式传递,
在调用函数中修改了参数的值,其改变会影响到实际的参数。
经典的例子就是2个数交换。
先看一下值传递:
/* * main.cpp * * Created on: 2012-9-17 * Author: china * * */ #include <iostream> using namespace std; void swap(int a,int b); int main(int argc, char **argv) { int x,y; cout<<"please enter two number:"; cin>>x>>y; cout<<x<<'\t'<<y<<endl; if (x<y) { swap(x,y); } cout<<x<<'\t'<<y<<endl; return 0; } void swap(int a,int b) { int temp; temp=a; a=b; b=temp; } 运行结果为: please enter two number:1 3 1 3 1 3
//其值不会交换。
再来看一下引用传递
/* * main.cpp * * Created on: 2012-9-17 * Author: china * *使用引用传递参数 * */ #include <iostream> using namespace std; void swap(int &a,int &b); int main(int argc, char **argv) { int x,y; cout<<"please enter two number:"; cin>>x>>y; cout<<x<<'\t'<<y<<endl; if (x<y) { swap(x,y); } cout<<x<<'\t'<<y<<endl; return 0; } void swap(int &a,int &b) { int temp; temp=a; a=b; b=temp; } 运行结果为: please enter two number:1 3 1 3 3 1 ================================
当然你还可以用指针变量作为函数参数,效果和引用传递一样。
/* * main.cpp * * Created on: 2012-9-17 * Author: china * * */ #include <iostream> using namespace std; void fun(int *a, int *b); int main(int argc, char **argv) { int a, b; cout << "please enter two number:"; cin >> a >> b; cout << a << '\t' << b << endl; fun(&a, &b); cout << a << '\t' << b << endl; return 0; } //将两个指针变量所指向的数值进行交换 void fun(int *a, int *b) { int t; t = *a; *a = *b; *b = t; } 运行及如果为: please enter two number:65 67 65 67 67 65 =======================================
你还可以交换指针变量所保存的地址哦。
/* * main.cpp * * Created on: 2012-9-17 * Author: china * * */ #include <iostream> using namespace std; int main(int argc, char **argv) { int a, b; cout << "please enter two number:"; cin >> a >> b; cout << a << '\t' << b << endl; int *p,*p1,*p2; p1=&a; p2=&b; cout << *p1 << '\t' << *p2 << endl; if(a<b)//交换地址 { p=p1; p1=p2; p2=p; } //指向发生变化 cout << a << '\t' << b << endl; cout << *p1 << '\t' << *p2 << endl; return 0; } 运行及如果为: please enter two number:56 67 56 67 56 67 56 67 67 56 ================================================
相关文章推荐
- Perl函数参数中传递数组和引用的使用
- 值类型与引用类型(特殊的string) Typeof和GetType() 静态和非静态使用 参数传递 相关知识
- C++ 使用const 引用传递参数
- Perl函数参数中传递数组和引用的使用
- C++引用(3) - 使用引用或者指针传递参数
- 二十二:通过引用向方法传递参数(使用out和ref参数)
- 通过引用向方法传递参数(使用out和ref参数)
- 使用表单传递参数,request处理参数出现"未将对象引用设置到对象的实例
- c#参数传递使用中的一个坑,值传递与引用传递
- Perl函数参数中传递数组和引用的使用
- 使用引用传递Mat参数 后类型发生变化
- jna对结构体、指针、引用、拷贝参数传递的使用
- C++ 使用const 引用传递参数
- 引用和使用引用传递参数《一》
- 不使用引用和全局变量实现函数参数传递
- Kotlin语言学习之将函数作为参数传递,使用双冒号::引用其他方法
- 传递引用类型参数
- java中参数传递详解:call by value(按值传递)和 call by reference(按引用传递)
- 拷贝构造函数的参数为什么必须使用引用类型
- Task Flow使用指南之一:在页面之间传递参数