【发布时间】:2019-10-11 18:48:49
【问题描述】:
在 C++ 中使用类时遇到一个奇怪的问题。
这是我将对象添加到我的链接列表的代码。我发现我的 V1 代码可以正常工作,但 V2 代码不能,并且 printList 永远不会在 V2 中停止。谁能解释为什么会这样,因为我希望 V1 和 V2 代码应该输出相同的结果。
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node *next;
Node() {
cout << "Node object is being created" << endl;
}
};
void printList(Node *node) {
while(node != NULL) {
cout << node->data << ",";
node = node->next;
}
cout << endl;
}
void push(Node **node, int data) {
// // working V1 start
// Node *newNode = new Node();
// newNode->data = data;
// newNode->next = *node;
// *node = newNode;
// // working V1 end
// not working V2 start
Node newNode;
newNode.data = data;
newNode.next = *node;
*node = &newNode;
// not working V2 end
}
int main() {
Node *a = NULL;
push(&a, 15);
push(&a, 10);
printList(a);
}
【问题讨论】:
-
对象在存储
Node newNode一旦执行退出它被声明的范围(方法体)就停止存在。这是语言的基础。