c++ 传值 传引用 与 传指针
#include <iostream>using namespace std;
// 函数声明void swap(int x, int y);
int main (){ // 局部变量声明 int a = 100; int b = 200;
// cout << " Before main, a is : " << a << endl;// cout << " Before main, b is : " << b << endl;
/* 调用函数来交换值 */ swap(a, b);
// 单纯的传值,只在调用的函数中改变值,原来的值并没有改变: cout << " Just copied a copy to the formal parameter, a is the same a, b is the same b"<< endl; cout << " After main, a is : " << a << endl; cout << " After main, b is : " << b << endl;
return 0;}
// 函数定义void swap(int x, int y){ int temp; cout << "--------Before swap --------:"<<endl; cout << x <<endl; cout << y <<endl; temp = x; /* 保存地址 x 的值 */ x = y; /* 把 y 赋值给 x */ y = temp; /* 把 x 赋值给 y */ cout << "--------After swap --------:"<<endl; cout << x <<endl; cout << y <<endl; return;}
// 1 传值,传递实参,即单纯的传值,从内存使用的角度来说,传递实参,则会将数据拷贝过去(创建了副本),// 即swap()对传入的数据做任何修改,都不会影响main()。// 2 传引用// 作为形参的引用会指向形参,类似于指针,调用函数后,实现了真正的交换。swap()和main()都交换了。// 3 传指针// 类似于传引用// https://www.runoob.com/cplusplus/passing-parameters-by-references.html

