【C++】引用交换实践作业

类内定义的交换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<iostream>
using namespace std;

//定义类
class _Swap{
private:
int a = 0;
int b = 1;
public:
void swap1();
void swap2();
void swap3();
};//这里要有分号!每一次都忘掉!

//这里老师强调要类外定义函数
void _Swap::swap1(){
int temp = 0;
temp = a;
a = b;
b = temp;
cout << "\t---swap1---" << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
}

void _Swap::swap2(){
int* pa = &a;
int* pb = &b;
int* temp;
cout << "\t---swap2---" << endl;
cout << "初始化:" << endl;
cout << "pa = " << *pa << ", &pa = " << pa << endl;
cout << "pb = " << *pb << ", &pb = " << pb << endl;
temp = pa;
pa = pb;
pb = temp;
cout << "交换后:" << endl;
cout << "pa = " << *pa << ", &pa = " << pa << endl;
cout << "pb = " << *pb << ", &pb = " << pb << endl;
}

void _Swap::swap3(){
int &ra = a;
int &rb = b;
cout << "\t---swap3---" << endl;
cout << "a = " << a << ", &a = " << &a << endl;
cout << "b = " << b << ", &b = " << &b << endl;
cout << "ra = " << ra << ", &pa = " << &ra << endl;
cout << "rb = " << rb << ", &pb = " << &rb << endl;
ra += rb;
rb = ra - rb;
ra -= rb;
cout << "交换后:" << endl;
cout << "a = " << a << ", &a = " << &a << endl;
cout << "b = " << b << ", &b = " << &b << endl;
cout << "ra = " << ra << ", &ra = " << &ra << endl;
cout << "rb = " << rb << ", &rb = " << &rb << endl;

}

int main(){
//定义对象
_Swap test;
//对象内类的函数调用
test.swap1();
test.swap2();
test.swap3();
}

按照实验要求写的程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include<iostream>
using namespace std;

//这里用了一个算法,没有使用中间变量过渡,而是通过运算进行交换
void swap1(int a,int b){
a += b;
b = a - b;
a -= b;
}

void swap2(int *a, int *b){
int *temp;
temp = a;
a = b;
b = temp;
}

void swap3(int& a,int& b){
a += b;
b = a - b;
a -= b;
}

int main(){
int x = 100;
int y = 200;
cout << "Before swap1:" << x << "," << y << endl;
swap1(x, y);
cout << "After swap1:" << x << "," << y << endl;

x = 100;
y = 200;
cout << "Before swap2:" << x << "," << y << endl;
swap2(&x, &y);
cout << "After swap2:" << x << "," << y << endl;

x = 100;
y = 200;
cout << "Before swap3:" << x << "," << y << endl;
swap3(x, y);
cout << "After swap3:" << x << "," << y << endl;
}

实验分析与总结

  1. 变量交换结果:

    1
    2
    Before swap1:100,200
    After swap1:100,200

    未成功交换,因为交换后的变量随函数栈释放了。

  2. 指针交换结果:

    1
    2
    Before swap2:100,200
    After swap2:100,200

    未成功交换,因为交换后的指针随函数栈释放了。

  3. 引用交换

    1
    2
    Before swap3:100,200
    After swap3:200,100

    成功交换!因为函数内外操作的是同一地址。

出错总结

  1. 定义类后一定要有;