所以我对指针有一个合理的理解,但我被问到这些是什么区别:
void print(int* &pointer)
void print(int* pointer)
Run Code Online (Sandbox Code Playgroud)
我自己还是学生,我不是100%.我很抱歉,如果这是基本但我的googleing技能让我失望.无论如何,你可以帮助我更好地理解这个概念.我很久没有使用过c ++了,我正在努力帮助一个学生,我正在努力为她巩固我的概念知识.
第一个通过引用传递指针,第二个按值传递.
如果使用第一个签名,则可以修改指针指向的内存以及指向的内存.
例如:
void printR(int*& pointer) //by reference
{
*pointer = 5;
pointer = NULL;
}
void printV(int* pointer) //by value
{
*pointer = 3;
pointer = NULL;
}
int* x = new int(4);
int* y = x;
printV(x);
//the pointer is passed by value
//the pointer itself cannot be changed
//the value it points to is changed from 4 to 3
assert ( *x == 3 );
assert ( x != NULL );
printR(x);
//here, we pass it by reference
//the pointer is changed - now is NULL
//also the original value is changed, from 3 to 5
assert ( x == NULL ); // x is now NULL
assert ( *y = 5 ;)
Run Code Online (Sandbox Code Playgroud)