Pointer reference and reference pointer difference

c ++ parameter passing in the process, the pointer ( ) and pointer references ( &) is different.
Although we often can then modify the value of the pointer points to an object through inter-access pass through a pointer, the same can also modify the value of an object directly by reference.
However, when the transfer pointer has a problem that, although we can modify the value of the pointer points to an object through a pointer, but we did not directly modify the contents of a pointer (which is a pointer variable to store the address), because the function parameter passing when the pointer is actually the copy again, although the address pointer inside the store or we would have the address of that object, but not the original pointer variable pointer variables.
So, when we want to address in a function to modify a pass over the pointer variable, you must use a pointer references, otherwise, this modification is "invalid"

Code:

#include<iostream>
using namespace std;
class Node {
public:
    int data;
};
void fun1(Node* node) {
    node = new Node();
    node->data = 2;
}

void fun2(Node*& node) {
    node = new Node();
    node->data = 2;
}

int main() {
    Node * node = new Node();
    node->data = 1;
    fun1(node);
    cout << "传指针并没有修改到该指针的值,而是新建了一个指针指向了一个新的对象" << endl;
    cout << node->data << endl;
    fun2(node);
    cout << "传指针引用把传进来的指针指向一个新的对象,并修改该对象的值" << endl;
    cout << node->data << endl;
    system("pause");
}

result

传指针并没有修改到该指针的值,而是新建了一个指针指向了一个新的对象
1
传指针引用把传进来的指针指向一个新的对象,并修改该对象的值
2
请按任意键继续. . .

Guess you like

Origin www.cnblogs.com/urahyou/p/11841124.html