use*_*284 3 c c++ pointers data-structures
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 ++代码中,调用后不会改变头部丢失吗?
这里的问题是你与C++比较的C代码并不是真正类似的.一个更好的例子是
typedef struct Node {
int data;
struct Node* pNext;
} Node;
typedef struct Stack {
Node* pHead;
} Stack;
void push(Stack* this, int data) {
Node* newNode = malloc (sizeof (Node));
newNode->data = data;
newNode->next = this->head;
this->head = newNode;
}
Run Code Online (Sandbox Code Playgroud)
在这个版本中,我们已成功实施,push而无需采取**头脑.我们在某种程度上是因为它是双向间接的Stack*.但这与C++的工作方式非常相似.可以将C++视为this函数的隐藏参数.