struct node {
int data;
struct node* next;
}
void push (struct node **head, int data) {
struct node* newNode = malloc (sizeof (struct node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
//I understand c version well.
C++ version
void Stack::push( void *data ) {
struct node *newNode = new node;
newNode->data = data;
newNode->next = head;
head = newNode;
}
Run Code Online (Sandbox Code Playgroud)
在c ++中,head是堆栈类的私有或受保护成员,并声明为node*head.
问题:为什么head可以在c ++中调用push()之后保留其值.
在c中,我们需要将其声明为**,因为我们想要在push()函数调用之后更改头指针的值.在c ++代码中,调用后不会改变头部丢失吗?