我試圖創建一個雙向鏈接列表,其中每個列表都有第一個節點,最後一個節點和num_elements。但是,出於某種原因,當我嘗試在UseList.cpp文件中測試代碼時,我無法將num_elements設置爲默認值爲零。不能讓構造函數運行
讓我告訴你我是什麼意思:
在List.h:
template <class L>
class List
{
private:
Node<L> *first;
Node<L> *last;
int num_elements;
public:
// constructors and destructors
List();
[...]
}
[...]
template <class L>
List<L>::List() {
first = NULL;
last = NULL;
num_elements = 0;
}
[...]
這是低下來list.h顯示方法:
template <class L>
// Print out the data in each node separated by a space.
void List<L>::show() {
cout << num_elements << endl;
Node<L> *current_node = first;
while (current_node != NULL) {
cout << current_node->data << " ";
current_node = current_node->next;
}
cout << endl;
}
注意,有是一個cout語句來打印num_elements。
這是UseList.cpp的相關部分:
int main (int argc, char *argv[]) {
cout << "-----------------------------------------" << endl;
cout << "----------------LIST ONE-----------------" << endl;
cout << "-----------------------------------------" << endl;
List<int> *list1;
srand(time(NULL));
list1->show();
[...]
當節目叫,它打印出「1」,並給了我一個分段錯誤。爲什麼num_elements默認爲「1」而不是「0」?
當我在List<L>::List() {
做了清點,沒有打印...(這意味着構造從來沒有運行?)
感謝您的幫助!
實例這是完美的。謝謝!一旦StackOverflow說10分鐘結束,我會接受答案。 –