指针的引用 *&

void swap(int* p1, int* p2) { // 这里的指针p1实际是副本
	cout << &p1 << " " << &p2 << endl;
}
void test() {
	int a = 1, b = 3;
	int* p1 = &a, * p2 = &b;
	cout << &p1 << " " << &p2 << endl;
	swap(p1, p2);
}

运行结果:

指针p1 p2地址:000000241AB8F708 000000241AB8F728
指针p1 p2地址:000000241AB8F6A0 000000241AB8F6A8

void swap(int* &p1, int* &p2) { // 
	cout << &p1 << " " << &p2 << endl;
}
void test() {
	int a = 1, b = 3;
	int* p1 = &a, * p2 = &b;
	cout << &p1 << " " << &p2 << endl;
	swap(p1, p2);
}

运行结果

指针p1 p2地址:000000D1371DFA78 000000D1371DFA98
指针p1 p2地址:000000D1371DFA78 000000D1371DFA98

结论:通俗来讲就是对指针进行引用,没有进行拷贝指针,在函数体内对指针的修改是全局的。

你可能感兴趣的:(c++)