C++关于引用的小知识
2016-12-20 16:10
337 查看
#include <iostream> using namespace std; void fun1(int b) { b = 1; } void fun2(int &b) { b = 2; } void fun3(int *b) { *b = 3; } void main() { int a = 0; fun1(a); cout << "调用fun1后,a的值为:" << a << endl; fun2(a); cout << "调用fun2后,a的值为:" << a << endl; fun3(&a); cout << "调用fun3后,a的值为:" << a << endl; }
下面3个不同的方法来加注理解
void swap1(int &a,int &b)
{
int t;
t = a;
a = b;
b = t;
}
int main()
{
int x = 5;
int y = 10;
cout << x << " " << y << endl;
swap1(x, y);
cout << x << " " << y << endl;// 结果是10,5
return 0;
}
void swap1(int a,int b) { int t; t = a; a = b; b = t; } int main() { int x = 5; int y = 10; cout << x << " " << y << endl; swap1(x, y); cout << x << " " << y << endl;// 结果是5,10,不是 引用,x和y的值压根就没有变化 return 0; }
void swap1(int &a,int b) { int t; t = a; a = b; b = t; } int main() { int x = 5; int y = 10; cout << x << " " << y << endl; swap1(x, y); cout << x << " " << y << endl;// 10,10 return 0; }
相关文章推荐
- c++ 关于引用&的一些知识
- 关于引用两篇之一 C++
- C++学习(4)--基础知识(4)--关于const
- C/C++中关于地址、指针和引用变量的学习笔记(二) : 数组
- C/C++中关于地址、指针和引用变量的学习笔记(七) : sizeof和typedef
- C/C++中关于地址、指针和引用变量的学习笔记(六) : const和void
- 关于C++准备知识
- 关于C++头文件的小知识
- 关于c++检测内存泄露相关知识(windows程序调试)
- 关于C++中函数返回引用的讨论
- C/C++中关于地址、指针和引用变量的学习笔记(九) : 内存结构
- C++学习(3)--基础知识(3)--关于操作符的重载
- C++ 关于声明,定义,类的定义,头文件作用,防止头文件在同一个编译单元重复引用,不具名空间
- 关于 C++ 引用 的面试题
- C/C++中关于地址、指针和引用变量的学习笔记(一)
- 关于在C++开发的项目中引用后缀名为.c文件的一句话提醒
- 关于在C++开发的项目中引用后缀名为.c文件的一句话提醒
- 关于“C++中产生随机数”(引用 http://hi.baidu.com/vincey/blog/item/5c145d08dd1e6d950a7b824b.html)
- C/C++中关于地址、指针和引用变量的学习笔记(四) : 函数
- C/C++中关于地址、指针和引用变量的学习笔记(十) : 引用型变量