【发布时间】:2021-01-20 17:35:21
【问题描述】:
我让 c++ 程序将数字作为输入,直到输入零并将它们保存为链表,然后打印出来,但我不明白为什么会出现这些错误。
代码如下:
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
};
int main()
{
Node* head = NULL, temp1, temp2;
int data = 1;
while(data)
{
cout<<"Enter number or 0 if you want to end : "<<endl;
cin>>data;
temp1 = (Node*)malloc(sizeof(Node));
temp2 = temp1;
if(head==NULL)
head = temp1;
else
temp2->next = temp1;
}
Node* temp1 = head->next;
while(temp1->next != NULL)
{
cout<<temp1->data<<endl;
temp1 = temp1 -> next;
}
return 0;
}
我收到这些错误:
test.cpp: In function 'int main()':
test.cpp:18:41: error: no match for 'operator=' (operand types are 'Node' and 'Node*')
temp1 = (Node*)malloc(sizeof(Node));
^
test.cpp:4:8: note: candidate: constexpr Node& Node::operator=(const Node&)
struct Node
^~~~
test.cpp:4:8: note: no known conversion for argument 1 from 'Node*' to 'const Node&'
test.cpp:4:8: note: candidate: constexpr Node& Node::operator=(Node&&)
test.cpp:4:8: note: no known conversion for argument 1 from 'Node*' to 'Node&&'
test.cpp:21:17: error: cannot convert 'Node' to 'Node*' in assignment
head = temp1;
^~~~~
test.cpp:23:15: error: base operand of '->' has non-pointer type 'Node'
temp2->next = temp1;
^~
test.cpp:25:10: error: conflicting declaration 'Node* temp1'
Node* temp1 = head->next;
^~~~~
test.cpp:12:23: note: previous declaration as 'Node temp1'
Node* head = NULL, temp1, temp2;
^~~~~
test.cpp:26:15: error: base operand of '->' has non-pointer type 'Node'
while(temp1->next != NULL)
^~
test.cpp:28:18: error: base operand of '->' has non-pointer type 'Node'
cout<<temp1->data<<endl;
^~
test.cpp:29:21: error: base operand of '->' has non-pointer type 'Node'
temp1 = temp1 -> next;
^~
【问题讨论】:
-
temp1 和 temp2 不是指针。 head 是一个指针。
-
在
Node* head = NULL, temp1, temp2;行中,您定位*的方式具有误导性。如果你这样写那行,你的错误会更明显:Node *head = NULL, temp1, temp2; -
一个定义,一个行的忠实粉丝。磁盘空间很便宜,可读性就像黄金一样。
-
C++ 有自己的内存管理(而且非常好),你不需要使用
malloc。 -
您应该更喜欢
new而不是malloc。运算符new调用构造函数,malloc不调用。
标签: c++ pointers linked-list nodes