函数按值传递和引用传递的有关问题
函数按值传递和引用传递的问题
#include <iostream>
using namespace std;
/*swap(float ,double);*/
int main()
{
int x;
int y;
cin>>x>>y;
cout<<endl;
cout<<x<<" "<<y<<endl;
swap(x,y);
cout<<x<<" "<<y<<endl;
return 0;
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
为什么不按引用传递 也能改变X,Y的值
??
------解决方案--------------------
您好,楼主的意思是按照你这个代码也能交换XY的值?
答案是否定的,也许是你看错了,又或者编译器出了问题,可以重启后再试,一般没有问题。
如果要改变可以用下面两种方式swap1和swap2:
#include <iostream>
using namespace std;
/*swap(float ,double);*/
int main()
{
int x;
int y;
cin>>x>>y;
cout<<endl;
cout<<x<<" "<<y<<endl;
swap(x,y);
cout<<x<<" "<<y<<endl;
return 0;
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
为什么不按引用传递 也能改变X,Y的值
??
------解决方案--------------------
您好,楼主的意思是按照你这个代码也能交换XY的值?
答案是否定的,也许是你看错了,又或者编译器出了问题,可以重启后再试,一般没有问题。
如果要改变可以用下面两种方式swap1和swap2:
- C/C++ code
/*A sample of swap two integer*/ #include <iostream> using namespace std; void swap1(int& a,int &b) { int temp; temp=a; a=b; b=temp; } void swap2(int*a,int*b) { int temp; temp=*a; *a=*b; *b=temp; } int main() { int x; int y; cin>>x>>y; cout<<endl; cout<<"未swap前"<<x<<" "<<y<<endl; swap1(x,y); cout<<"swap1之后"<<x<<" "<<y<<endl; swap2(&x,&y); cout<<"swap2之后"<<x<<" "<<y<<endl; return 0; }