當我編譯下面的代碼時,我得到“頭沒有命名型別”的編譯錯誤。有人可以解釋出了什么問題嗎?
#include <iostream>
using namespace std;
/* Link list node */
struct node {
int val;
struct node* next;
node(int x)
{
this->val = x;
next = NULL;
}
};
struct node *head = new node(3);
head -> next = new node(4); // error: head does not name a type.
head -> next->next = new node(5); // error: head does not name a type.
void print(){
struct node* temp = head;
while (temp != NULL) {
cout << temp->val << " ";
temp = temp->next;
}
}
int main()
{
print();
return 0;
}
我無法弄清楚為什么我會收到錯誤訊息。請有人幫幫我。
uj5u.com熱心網友回復:
在函式之外只允許宣告。諸如head->next = node(4)
需要在函式內部的運算式。您應該將該代碼移動到main()
.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/470100.html