对C++的一些基础用法理解不深,这一次就拿C++传递值来开个头,以后把C++的基本知识搞清楚。牛人轻拍。
#include <iostream>
using namespace std;
void swap(int* a,int* b)//指针传递,*号表示主函数实参的地址
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void swap_cite(int &a,int &b)//引用传递,间接寻址主函数实参变量
{
int temp;
temp = a;
a = b;
b = temp;
}
void main()
{
int x,y;
printf("Enter x,y:\n");
scanf("%d %d",&x,&y);
printf("original data:x=%d,y=%d\n",x,y);
swap(&x,&y);
printf("after swap:x=%d,y=%d\n",x,y);
printf("--------------------------\n");
swap_cite(x,y);
printf("after swap_cite:x=%d,y=%d\n",x,y);
}运行结果:
Enter x,y:
2 8
original data:x=2,y=8
after swap:x=8,y=2
--------------------------
after swap_cite:x=2,y=8
Press any key to continue
本文详细解析了C++中指针与引用传递的机制,通过实例展示了它们在参数交换中的应用,帮助读者深入理解C++基础用法。
5407

被折叠的 条评论
为什么被折叠?



