節點類如下:
class node
{
public:
int data; //the datum
node *next; //a pointer pointing to node data type
};
PrintList 函式如下:
void PrintList(node *n)
{ while (n != NULL)
{
cout << n->data << endl;
n = n->next;
}
}
如果我嘗試運行它,我會得到所有三個值(1,2,3),但我也得到了一個額外的數字,我無法弄清楚它代表什么,有人可以點亮它嗎?
int main()
{
node first, second, third;
node *head = &first;
node *tail = &third;
first.data = 1;
first.next = &second;
second.data = 2;
second.next = &third;
third.data = 3;
PrintList(head);
}
我知道它可以用
third.next = NULL;
但我只是好奇這個數字在輸出中代表什么,如果我省略上面的行
1
2
3
1963060099
uj5u.com熱心網友回復:
如 prapin 的評論中所述,third.next未初始化。C 有一個零開銷規則。自動初始化變數將違反此規則,因為該值可能會在稍后(第二次)初始化或什至永遠不會被使用。
的值third.next只是碰巧與現在位于同一記憶體位置的資料third.next。因此,建議始終自己初始化變數。
uj5u.com熱心網友回復:
最好初始化變數 & 最好使用nullptr. 像這樣(見1-3):
#include <iostream>
class node
{
public:
int data = 0; // 1
node* next = nullptr; // 2
};
void PrintList(node* n)
{
while (n != nullptr) // 3
{
std::cout << n->data << std::endl;
n = n->next;
}
}
int main()
{
node first, second, third;
node* head = &first;
node* tail = &third;
first.data = 1;
first.next = &second;
second.data = 2;
second.next = &third;
third.data = 3;
// third.next points to where?
PrintList(head);
}
補充說明:
我更喜歡使用 STL 容器std::list:
#include <list>
#include <iostream>
std::list<int> int_list;
void PrintList()
{
for (auto i : int_list)
std::cout << i << std::endl;
}
int main()
{
int_list.push_back(1);
int_list.push_back(2);
int_list.push_back(3);
PrintList();
}
或者在它是node物件串列的情況下:
#include <list>
#include <iostream>
class node
{
public:
node(int data) : m_data{ data } {};
int m_data = 0;
// and maybe extra data-members
};
std::list<node> node_list;
void PrintList()
{
for (auto i : node_list)
std::cout << i.m_data << std::endl;
}
int main()
{
node_list.push_back(node(1));
node_list.push_back(node(2));
node_list.push_back(node(3));
PrintList();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/334846.html
上一篇:將引數傳遞給C中的結構
