Hi, I'm a programming beginner. I'm trying to learn C++ Abstract Data Types, where I'm using the template <class T> to make a stack. Here's the code:
main.cpp:
#include <iostream>
#include "H.h"
using namespace std;
int main() {
List<int> myList;
myList.insert_head();
myList.insert_head();
myList.insert_head();
myList.print_list();
myList.remove_head();
myList.print_list();
return 0;
}
Here's, my header file
H.h:
#pragma once
#define NEXT_LINE cout << endl;
using namespace std;
template <class T>
class List;
template <class T>
class ListNode {
private:
int item;
ListNode<T> *next;
public:
friend class List<T>;
ListNode();
~ListNode();
};
template <class T>
class List {
private:
int size;
ListNode<T> *head;
public:
List();
~List();
void insert_head();
void remove_head();
void print_list();
};
And finally, here's my List.cpp:
#include <iostream>
#include "H.h"
using namespace std;
template <class T>
List<T>::List() {
size = 0;
head = NULL;
}
template <class T>
List<T>::~List() {
cout << "Destructor:" << endl;
while (size > 0) {
remove_head();
}
cout << "Successfully deleted Linked List";
}
template <class T>
void List<T>::insert_head() {
ListNode<T> *aNewNode = new ListNode<T>;
aNewNode->next = head;
head = aNewNode;
size++;
}
template <class T>
void List<T>::remove_head() {
int what_item = head->item;
if (size > 0) {
ListNode<T> *temp = head;
head = head->next;
delete temp;
size--;
}
cout << "Removed node containing: " << what_item << endl;
}
template <class T>
void List<T>::print_list() {
NEXT_LINE
ListNode<T> *ptr = head;
cout << "The items in the list are:" << endl;
while (ptr != NULL) {
cout << ptr->item << endl;
ptr = ptr->next;
}
NEXT_LINE
}
template <class T>
ListNode<T>::ListNode() {
cout << "Input Integer: ";
cin >> item;
next = NULL;
}
template <class T>
ListNode<T>::~ListNode() {
}
I keep getting the following errors:
/usr/bin/ld: /tmp/ccPECyJI.o: in function `main':
main.cpp:(.text+0x24): undefined reference to `List::List()'
/usr/bin/ld: main.cpp:(.text+0x30): undefined reference to `List::insert_head()'
/usr/bin/ld: main.cpp:(.text+0x3c): undefined reference to `List::insert_head()'
/usr/bin/ld: main.cpp:(.text+0x48): undefined reference to `List::insert_head()'
/usr/bin/ld: main.cpp:(.text+0x54): undefined reference to `List::print_list()'
/usr/bin/ld: main.cpp:(.text+0x60): undefined reference to `List::remove_head()'
/usr/bin/ld: main.cpp:(.text+0x6c): undefined reference to `List::print_list()'
/usr/bin/ld: main.cpp:(.text+0x7d): undefined reference to `List::~List()'
/usr/bin/ld: main.cpp:(.text+0xa3): undefined reference to `List::~List()'
collect2: error: ld returned 1 exit status
Please help me!
Thank you!