Monday, July 23, 2018

Template in C++




I am trying to implement a singly linked list that stores multiple types of item. So I came across templates, but when I tried running the following code, the compiler gives me several linking errors (LNK 2019: unresolved external symbol). I haven't really done anything yet and can't figure out what went wrong. Can anyone please point out my mistake??




singlylinkedlist.h



template 
class SinglyLinkedList
{
public:
SinglyLinkedList();
~SinglyLinkedList();

private:

template
struct Node {
I item;
Node *next;
};

Node *head;
};


singlylinkedlist.cpp




#include "singlylinkedlist.h"

template

SinglyLinkedList::SinglyLinkedList()
{
head = NULL;
}



main.cpp



#include 
#include "singlylinkedlist.h"

using namespace std;

int main()
{
SinglyLinkedList list;

}

Answer



There are a number of small issues with the code, for example, you haven't implemented the destructor, and you don't really need to templatize Node. Change your implementation as follows,



// singlylinkedlist.h
template
class SinglyLinkedList
{
public:

SinglyLinkedList() : head(NULL) {}
~SinglyLinkedList() {}

private:
struct Node {
Item item;
Node *next;
};
Node *head;
};


// main.cpp
#include "singlylinkedlist.h"
using namespace std;

int main()
{
SinglyLinkedList list;
}


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...