注册 登录
编程论坛 C++教室

请问这两个程序有什么区别?求解

飘羽 发布于 2011-03-25 11:55, 351 次点击
程序1
#include <iostream.h>
void Swap(char* str1, char* str2);
void main()
{
  char* ap="hello";
  char* bp="how are you?";
  cout <<ap <<endl <<bp <<endl;
  Swap(ap, bp);
   cout <<"交换以后:\n";
  cout <<ap <<endl <<bp <<endl;
}
void Swap(char* str1, char* str2)
{  char* temp=str1;
      str1=str2;  str2=temp;
}
程序2
#include <iostream.h>
void Swap(char*& str1, char*& str2);
void main()
{
  char* ap="hello";
  char* bp="how are you?";
  cout <<ap <<endl <<bp <<endl;
  Swap(ap, bp);
   cout <<"交换以后:\n";
  cout <<ap <<endl <<bp <<endl;
}
void Swap(char*& str1, char*& str2)
{  char* temp=str1;
      str1=str2;  str2=temp;
}
3 回复
#2
yuccn2011-03-25 13:20
上面的没有实现交换,
下面的才能交换。
char* ap="hello";
char* bp="how are you?";

Swap(ap, bp);

实质上,等价于:
char* ap="hello";
char* bp="how are you?";
{
  char* str1 = ap;
  char* str2 = bp;

  char* temp=str1;
  str1=str2;
  str2=temp;
 }

调用Swap后,实质上是改变了两个临时指针变量所指的内存位置,原来的ap 和bp指向位置没有变

后面的实质上就是把ap 和bp的地址传进去,也就是
char* ap="hello";
char* bp="how are you?";
{
  char* temp=ap;
  ap=bp;
  bp=temp;
 }
故实现了指向的位置值交换了






[ 本帖最后由 yuccn 于 2011-3-25 18:54 编辑 ]
#3
yuccn2011-03-25 13:23
回复 楼主 飘羽
如果还不明白就先理解下两个函数的差别吧,差不多的
void swap(int a, int b)
{
  int temp = a;
  a = b;
  b = temp;
}


void swap(int *a, int *b)
{
  int temp = *a;
  *a = *b;
  *b = temp;
}
#4
pangding2011-03-25 14:24
2,3楼 解释的已经比较到位了。
1