实例1:值传递
1 #include<iostream>
2
3 void changeAge(int age,int newAge);
4 int main()
5 {
6 int age = 24;//定义一个age,占一处地址
7 std::cout << "My age is " << age <<"\n";
8
9 changeAge(age,age + 1);
10
11 std::cout << "Now my age is " << age << "\n";
12
13 return 0;
14 }
15
16 void changeAge(int age,int newAge)//再定义一个age,占另一处地址
17 {
18 age = newAge;
19 std::cout << "In this, my age is " << age << "\n";
20 }
绕开“值传递”问题的第一种方法是向函数传递变量的地址取代他的值。
实例2:指针地址传递
1 #include<iostream>
2
3 void changeAge(int *age,int newAge);
4 int main()
5 {
6 int age = 24;//定义一个age,占一处地址
7 std::cout << "My age is " << age <<"\n";
8
9 changeAge(&age,age + 1);
10
11 std::cout << "Now my age is " << age << "\n";
12
13 return 0;
14 }
15
16 void changeAge(int *age,int newAge)//再定义一个age,占另一处地址
17 {
18 *age = newAge;
19 std::cout << "In this, my age is " << *age << "\n";
20 }
实例3:两值互换
1 #include<iostream>
2
3 void swap(int *x,int *y);
4 int main()
5 {
6 int x,y;
7
8 std::cout << "请输入两个不同的值:";
9 std::cin >> x >> y;
10
11 swap(&x,&y);
12
13 std::cout << "调换后输出:" << x << ' ' << y <<"\n\n";
14
15 }
16
17 void swap(int *x,int *y)
18 {
19 int temp;
20 temp = *x;
21 *x = *y;
22 *y = temp;
23 }
实例4:两值互换2
1 #include<iostream>
2
3 void swap(int *x,int *y);
4 int main()
5 {
6 int x,y;
7
8 std::cout << "请输入两个不同的值:";
9 std::cin >> x >> y;
10
11 swap(&x,&y);
12
13 std::cout << "调换后输出:" << x << ' ' << y <<"\n\n";
14
15 }
16
17 void swap(int *x,int *y)
18 {
19 *x ^= *y;
20 *y = *x;
21 *x ^= *y;
22 }
实例5:不用指针的两值交换
1 #include <iostream>
2
3 void swap(int &x,int &y);
4
5 int main()
6 {
7 int x,y;
8 std::cout << "请输入两个不同的值:";
9 std::cin >> x >> y;
10
11 swap(x,y);
12 std::cout << "调换后输出:" << x << ' ' << y << "\n\n";
13
14 return 0;
15 }
16
17 void swap(int &x,int &y)
18 {
19 int temp;
20 temp = x;
21 x = y;
22 y = temp;
23 }