值传递

  1. // 值传递
  2. void fun(int x)
  3. {
  4. x += 5; //修改的只是y在栈中copy x,x只是y的一个副本,在内存中重新开辟的一块临时空间把y的值 送给了x;这样也增加程序运行时间,降低了程序的效率
  5. }
  6. int main()
  7. {
  8. int y = 0;
  9. fun(y);
  10. cout<< "y = " << y << endl; //y = 0;
  11. }

指针传递

  1. // 指针传递
  2. void fun(int *x)
  3. {
  4. *x += 5; //修改的是指针x指向的内存单元值
  5. }
  6. int main()
  7. {
  8. int y = 0;
  9. fun(&y);
  10. cout<<"y = "<<y<<endl; //y = 5;
  11. }

引用传递

  1. // 引用传递
  2. void fun(int &x)
  3. {
  4. x += 5; //修改的是x引用的对象值 &x = y;
  5. }
  6. int main()
  7. {
  8. int y = 0; //引用的实参必须初始化
  9. fun(y);
  10. cout<<"y = "<<y<<endl; //y = 5;
  11. }

& 取地址符号

  1. // 关于&的举例
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. char a, b, c;
  5. int main()
  6. {
  7. a = 'a', b = 'b', c = 'c';
  8. cout << &a << '\n';
  9. return 0;
  10. }
  1. // 代码1
  2. #include <iostream>
  3. using namespace std;
  4. void swap(int a, int b)
  5. {
  6. int t = a;
  7. a = b;
  8. b = t;
  9. }
  10. int main()
  11. {
  12. int a = 1, b = 2;
  13. swap(a, b);
  14. cout << a << ' ' << b << '\n';
  15. return 0;
  16. }
  17. /*
  18. 1 2
  19. */
  1. // 代码2
  2. #include <iostream>
  3. using namespace std;
  4. void swap(int &a, int &b)
  5. {
  6. int t = a;
  7. a = b;
  8. b = t;
  9. }
  10. int main()
  11. {
  12. int a = 1, b = 2;
  13. swap(a, b);
  14. cout << a << ' ' << b << '\n';
  15. return 0;
  16. }
  17. /*
  18. 2 1
  19. */
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. void f(char *a, char *b)
  4. {
  5. a = b;
  6. (*a)++;
  7. }
  8. int main()
  9. {
  10. char c1, c2;
  11. char *p1, *p2;
  12. c1 = 'A', c2 = 'a';
  13. p1 = &c1, p2 = &c2;
  14. f(p1, p2);
  15. cout << c1 << ' ' << c2 << '\n';
  16. return 0;
  17. }