值传递和引用传递
” 按值传递 “中包括值传递(实实在在的值啊!)和指针传递(指针传递参数本质上是值传递的方式,它所传递的是一个地址值),传递的都是实参的一个拷贝。
#include <iostream>
using namespace std;
void swap(int x, int y) {
int tmp;
tmp = x;
x = y;
y = tmp;
}
int main() {
int a = 2, b = 3;
printf("before:%d,%d\n", a, b);
swap(a, b);
printf("later:%d,%d\n", a, b);
return 0;
}
结果:
before:2,3
later:2,3
下面的例子体现了不论传递的是值还是指针 (指针也是一个值),传递给被调用函数的都是实参的一个拷贝,直接对拷贝进行操作不会影响实参
#include <iostream>
using namespace std;
void swap(int *x, int *y) {
cout<<"函数内-start"<<endl;
cout<<"*x:"<<*x<<" *y:"<<*y<<endl;
cout<<"&x:"<<&x<<" &y:"<<&y<<endl;
cout<<"x:"<<x<<" y:"<<y<<endl;
cout<<"开始交换"<<endl;
int *temp= NULL; //因为x,y的类型都是int *
temp= x; //temp= &a &a:0x61fe1c &b:0x61fe18
x = y; // &a= &b
y = temp; //&b=temp
//所以交换x,y只是交换了两者存储的值(值为&a,&b),并没有涉及到主函数a,b值的交换
//所以只是操作地址并没有卵用
cout<<"*x:"<<*x<<" *y:"<<*y<<endl;
cout<<"&x:"<<&x<<" &y:"<<&y<<endl;
cout<<"x:"<<x<<" y:"<<y<<endl;
cout<<"函数内-end"<<endl;
}
int main() {
int a = 2, b = 3;
cout<<"before a:"<<a<<" b:"<<b<<endl;
cout << "before &a:" << &a << " &b:" << &b << endl;
swap(&a, &b);
cout<<"later a:"<<a<<" b:"<<b<<endl;
cout << "later &a:" << &a << " &b:" << &b << endl;
return 0;
}
结果
before a:2 b:3
before &a:0x61fe1c &b:0x61fe18
函数内-start
*x:2 *y:3 //0x61fe1c->2,0x61fe18->3
&x:0x61fdf0 &y:0x61fdf8
x:0x61fe1c y:0x61fe18
开始交换
*x:3 *y:2 //0x61fe1c->2,0x61fe18->3
&x:0x61fdf0 &y:0x61fdf8
x:0x61fe18 y:0x61fe1c
函数内-end
later a:2 b:3
later &a:0x61fe1c &b:0x61fe18
#include <iostream>
using namespace std;
void swap(int *x, int *y) {
cout<<"函数内-start"<<endl;
cout<<"*x:"<<*x<<" *y:"<<*y<<endl;
cout<<"&x:"<<&x<<" &y:"<<&y<<endl;
cout<<"x:"<<x<<" y:"<<y<<endl;
cout<<"开始交换"<<endl;
int temp;
//*x作用就是:取指针x的值(&a),再把这个值作为地址,再取这个地址的值!相当于*(&a)=a
temp= *x; //temp=a
*x = *y; //a=b
*y = temp; //b=temp
cout<<"*x:"<<*x<<" *y:"<<*y<<endl;
cout<<"&x:"<<&x<<" &y:"<<&y<<endl;
cout<<"x:"<<x<<" y:"<<y<<endl;
cout<<"函数内-end"<<endl;
}
int main() {
int a = 2, b = 3;
cout<<"before a:"<<a<<" b:"<<b<<endl;
cout<<"before &a:"<<&a<<" &b:"<<&b<<endl;
swap(&a, &b);
cout<<"later a:"<<a<<" b:"<<b<<endl;
cout<<"later &a:"<<&a<<" &b:"<<&b<<endl;
return 0;
}
结果:
before a:2 b:3
before &a:0x61fe1c &b:0x61fe18
函数内-start
*x:2 *y:3
&x:0x61fdf0 &y:0x61fdf8
x:0x61fe1c y:0x61fe18
开始交换
*x:3 *y:2
&x:0x61fdf0 &y:0x61fdf8
x:0x61fe1c y:0x61fe18
函数内-end
later a:3 b:2
later &a:0x61fe1c &b:0x61fe18
陈异铥:文章真不错http://meig.1ut9wd.cn
博主真是太厉害了!!!
叼茂SEO.bfbikes.com
怎么收藏这篇文章?
不错不错,我喜欢看 https://www.237fa.com/
不错不错,我喜欢看 https://www.237fa.com/
看的我热血沸腾啊https://www.ea55.com/
想想你的文章写的特别好www.jiwenlaw.com
哈哈哈,写的太好了https://www.cscnn.com/