Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4463094
  • 博文数量: 1148
  • 博客积分: 25453
  • 博客等级: 上将
  • 技术积分: 11949
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-06 21:14
文章分类

全部博文(1148)

文章存档

2012年(15)

2011年(1078)

2010年(58)

分类: C/C++

2011-05-24 17:30:05

page 227

  1. #include <iostream>

  2. void swapr(int &a, int &b);
  3. void swapp(int *p, int *q);
  4. void swapv(int a, int b);

  5. int main()
  6. {
  7.     using namespace std;

  8.     int wallet1 = 300;
  9.     int wallet2 = 350;

  10.     cout << "wallet1 =$" << wallet1;
  11.     cout << "wallet2 =$" << wallet2 << endl << endl;

  12.     //引用
  13.     cout << "using references to swap contents:\n";
  14.     swapr(wallet1, wallet2); //引用
  15.     cout << "wallet1 =$ " << wallet1;
  16.         cout << "wallet2 =$ " << wallet2 << endl << endl;

  17.     //指针
  18.     cout << "using pointers to swap contents:\n";
  19.         swapp(&wallet1, &wallet2); //指针
  20.         cout << "wallet1 =$ " << wallet1;
  21.         cout << "wallet2 =$ " << wallet2 << endl << endl;

  22.     //传值
  23.     cout << "using references to swap contents:\n";
  24.         swapv(wallet1, wallet2); //
  25.         cout << "wallet1 =$" << wallet1;
  26.         cout << "wallet2 =$" << wallet2 <<endl;

  27.     return 0;
  28. }


  29. void swapr(int &a, int &b)
  30. {
  31.     int tmp;
  32.     tmp = a;
  33.     a = b;
  34.     b = tmp;
  35. }

  36. void swapp(int *p, int *q)
  37. {
  38.     int tmp;
  39.     tmp = *p;
  40.     *p = *q;
  41.     *q = tmp;
  42. }

  43. void swapv(int a, int b)
  44. {
  45.     int tmp;
  46.     tmp = a;
  47.     b = a;
  48.     a = tmp;
  49. }
  1. ywx@yuweixian:~/yu/c++$ ./swaps
  2. wallet1 =$300wallet2 =$350        

  3. using references to swap contents:
  4. wallet1 =$ 350wallet2 =$ 300        引用 改变

  5. using pointers to swap contents:
  6. wallet1 =$ 300wallet2 =$ 350         指针 改变

  7. using references to swap contents:
  8. wallet1 =$300wallet2 =$350           值传递 没有改变

阅读(985) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~