我写了一个程序,大家帮我看看哪里有问题
// test5.4.cpp : demonstrates passing by value#include "stdafx.h"
#include "iostream"
using namespace std;
void swap(int x, int y);
int main()
{
int x = 5,y = 10;
cout <<"Main.Before swap, x: "<< x <<" y: "<< y << endl;
swap(x,y);
cout <<"Main.After swap, x: "<< x <<" y: "<< y << endl;
return 0;
}
void swap(int x, int y)
{
int temp;
cout <<"Swap.Before swap,x: "<< x <<" y: "<< y << endl;
temp = x;
x = y;
y = temp;
cout <<"Swap.After swap,x: "<< x <<" y: "<< y << endl;
}
包含的头文件有问题
#include "stdafx.h" 不需要用这个;#include "iostream" 改为#include<iostream> 因为这是库里面的,而不是你自己定义的. 交换值能实现吗?swap()函数中的形式参数用引用比较好吧,呵呵~~~ 什么问题都没有
如果不能运行可能是编译器有问题 这肯定不能交换数据啊
1.不需要#include "stdafx.h"
子函数改成一下就行了
void swap(int &x, int &y)
{
int temp;
cout <<"Swap.Before swap,x: "<< x <<" y: "<< y << endl;
temp = x;
x = y;
y = temp;
cout <<"Swap.After swap,x: "<< x <<" y: "<< y << endl;
} 楼上的看清人家的意图好不好!!
误区
你没有弄清楚什么是按值传递和按引用传递,再看下书 #include "iostream"using namespace std;
void swap(int *, int *);
int main()
{
int x = 5,y = 10;
cout <<"Main.Before swap, x: "<< x <<" y: "<< y << endl;
swap(&x,&y);
cout <<"Main.After swap, x: "<< x <<" y: "<< y << endl;
return 0;
}
void swap(int *x, int *y)
{
int temp;
cout <<"Swap.Before swap,x: "<< *x <<" y: "<< *y << endl;
temp = *x;
*x = *y;
*y = temp;
cout <<"Swap.After swap,x: "<< *x <<" y: "<< *y << endl;
}
页:
[1]
