![](/img/trans.png)
[英]Why are we using pointer to pointer for one and a normal pointer to another?
[英]why cannot we initialize a node without using a pointer?
我最近開始學習數據結構,作為初學者,我在實現鏈表節點時有一個疑問,為什么我們必須只使用指針來初始化節點?
class node{
public:
int data;
node* next;
node(int val){
data = val;
next = NULL;
}
};
int main(){
node* head = NULL;
node head = NULL; // this throws an error which i cannot understand
}
實際上你可以按值初始化節點。 如果你想用值初始化一個節點,根據你的構造函數node(int val)
,你必須像下面這樣編碼:
class node{
public:
int data;
node* next;
explicit node(int val){
data = val;
next = NULL;
}
};
int main(){
int value = 777;
//node* head = NULL; // Initialize head pointers to null
node head(value); // By your constructor definition
}
編輯:順便說一句,將構造函數標記為顯式是一個非常好的習慣,因為它可以防止意外轉換,正如 Duthomhas 評論的那樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.