在C语音中*代表指针,&代表地址
在C++中*代表指针,而&代表引用,而*&代表指针引用
复习一下,指针是一个变量(它的值是一个地址),而指针引用指的是这个变量的引用;在C++中如果参数不是引用的话会调用参数对象的拷贝构造函数,所以如果有需求想改变指针所指的对象(换句话说,就是要改变指针里面存的地址),就要使用指针引用,在网上看到大佬的代码,简单明了,如下
#include <iostream>
using namespace std;
struct Point {
int x;
int y;
};
/*指针*/
void test1(Point *p)
{
p = new Point();
p->x = 100;
}
/*指针引用*/
void test2(Point *&p)
{
p = new Point();
p->x = 100;
}
int main(int argc, char const *argv[])
{
Point *p1 = new Point();
Point *p2 = new Point();
p1->x = 1;
p2->x = 1;
cout << "p1->x = " << p1->x << "; p2->x = " << p2->x << endl;
test1(p1);
test2(p2);
cout << "p1->x = " << p1->x << "; p2->x = " << p2->x << endl;
return 0;
}
执行结果
yishurufa@ubuntu:~/works/program$ vim test.cpp
yishurufa@ubuntu:~/works/program$ g++ test.cpp
yishurufa@ubuntu:~/works/program$ ./a.out
p1->x = 1; p2->x = 1
p1->x = 1; p2->x = 100