Вопрос

How do I declare an instance of the linked list with the data type of a struct in main? For example... I am supposed to have a class with a struct that holds info. The linkedlist is supposed to have a data type of the struct. This is the instruction: The DVD class has the structure and one of its data members is an instance of the linked list with that structure as the data type.

class DVD
{
private:
struct disc
{
int length;
string name;
};

Linked List

template <class T>
class LinkedList1 
{
private:
// Declare a structure
struct discList
{
    T value;
    struct discList *next;  // To point to the next node
};

discList *head;     // List head pointer

public:
// Default Constructor
LinkedList1()
{ head = NULL; }


// Destructor
~LinkedList1();

// Linked list operations
void appendNode(T);
void insertNode(T);
void deleteNode(T);
void displayList() const;
};
Это было полезно?

Решение

all you have to do is to specify the type between angle brackets, like this:
LinkedList1<DVD> myLinkedList;

EDIT:

Here is what is happening behind the scene, the compiler will replace each T with DVD.

getting back to your code we get this:

struct discList
{
    DVD value; // You used to have T here
    struct discList *next;  // To point to the next node
};

and you will have a linked list where each node is a structure holding a DVD value.

Другие советы

The name of the structure shall be accessible for the template class.

You could define this structure separatly and use its definition simultaneously in class DVD and as the template argument of the template class, For example

struct disc
{
int length;
string name;
};


class DVD
{
private:
   disc obj;
};

and then

LinkedList<disc> l;

Or you could define a public typedef for structure disc in class DVD. For example

class DVD
{
private:
struct disc
{
int length;
string name;
};
public:
  typedef disc disc_t;
};


LinkedList<DVD::disc_t> l;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top