Почему я получаю ошибки компиляции, когда я пытаюсь сделать этот конструктор generi c? - PullRequest
0 голосов
/ 19 марта 2020

Итак, у меня есть эти три класса

template <class dataType>
class listEntry
{

      private:
              dataType data;
      public:
              listEntry *next;
              listEntry *prev;

              dataType getData() { return this->data; }

              listEntry();
              listEntry(dataType data) { this->data = data; }
              ~listEntry() {};    

};

template <class dataType>
class List
{

      private:
              dataType *head;
              dataType *tail;
              int count;
      public:
             dataType *getHead() { return this->head; }
             dataType *getTail() { return this->tail; }

             void addToTail(dataType *newEntry);
             void addToHead(dataType *newEntry);

             int getCount() { return count; }

             void printListForward();

             List();
             List(const List<dataType> &li);
             ~List();  

};

template <class dataType>
class Queue: public List<dataType>
{

      public:
             void enQueue(dataType *newEntry);

             Queue():List<dataType>() { return; }
             Queue(const List<dataType>& li):List<dataType>(li) { return; }
             Queue(dataType data);
             Queue(listEntry<dataType> le);

}

И один из моих конструкторов для очереди таков:

template <class dataType>
Queue<dataType>::Queue(dataType data)
{

  enQueue(new listEntry<int>(data));                               

}

Однако я хочу, чтобы enQueue(new listEntry<int>(data)); было enQueue(new listEntry<dataType>(data)); так что он является общим c и может работать с любым типом данных. Но когда я изменяю его на это, я получаю ошибки компиляции.

Определение enQueue выглядит так:

template <class dataType>
void Queue<dataType>::enQueue(dataType *newEntry)
{

     this->addToTail(newEntry);     

}

Почему запись dataType вместо int приводит к ошибкам компиляции?

1 Ответ

0 голосов
/ 19 марта 2020

Есть некоторые проблемы с дизайном вашего кода:

  • head и tail члены List должны быть объявлены как listEntry<dataType>* вместо dataType*.

  • addToTail(), addToHead() и enQueue() должны принимать dataType значения вместо dataType* указателей.

  • addToTail() и addToHead() необходимо создать новый объект listEntry<dataType> для внутреннего использования.

Вместо этого попробуйте что-нибудь еще подобное:

template <class dataType>
class listEntry
{
private:
    dataType data;
public:
    listEntry *prev;
    listEntry *next;

    dataType getData() const { return data; }

    listEntry(const dataType &data, listEntry *prev = NULL, listEntry *next = NULL);
};

template <class dataType>
class List
{
public:
    typedef listEntry<dataType> entryType;
private:
    entryType *head;
    entryType *tail;
    int count;
public:
    entryType* getHead() { return head; }
    const entryType* getHead() const { return head; }

    entryType* getTail() { return tail; }
    const entryType* getTail() const { return tail; }

    void addToTail(const dataType &data);
    void addToHead(const dataType &data);

    int getCount() const { return count; }

    void printListForward() const;

    List();
    List(const List &li);
    ~List();  

    List& operator=(const List &li);
};

template <class dataType>
class Queue : public List<dataType>
{
public:
    typedef List<dataType> listType;

    void enQueue(const dataType &data);

    Queue() {}
    Queue(const Queue &q) : listType(q) {}
    Queue(const listType &li) : listType(li) {}
    Queue(const dataType &data);
};

...

template<class dataType>
listEntry<dataType>::listEntry(const dataType &data, listEntry *prev, listEntry *next)
    : data(data), prev(prev), next(next)
{
}

template<class dataType>
void List<dataType>::addToTail(const dataType &data)
{
    entryType *newEntry = new entryType(data, tail);
    if (!head) head = newEntry;
    if (tail) tail->next = newEntry;
    tail = newEntry;
    ++count;
}

template<class dataType>
void List<dataType>::addToHead(const dataType &data)
{
    entryType *newEntry = new entryType(data, NULL, head);
    if (!tail) tail = newEntry;
    if (head) head->prev = newEntry;
    head = newEntry;
    ++count;
}

template<class dataType>
void List<dataType>::printListForward() const
{
    entryType *entry = head;
    while (entry)
    {
        //...
        entry = entry->next;
    }
}

template<class dataType>
void List<dataType>::List()
    : head(NULL), tail(NULL), count(0)
{
}

template<class dataType>
void List<dataType>::List(const List<dataType> &li)
    : head(NULL), tail(NULL), count(0)
{
    const entryType *entry = li.getHead();
    while (entry)
    {
        addToTail(entry->getData());
        entry = entry->next;
    }
}

template<class dataType>
void List<dataType>::~List()
{
    entryType *entry = head;
    while (entry)
    {
        entryType *next = entry->next;
        delete entry;
        entry = next;
    }
}

template<class dataType>
List<dataType>& List<dataType>::operator=(const List<dataType> &li)
{
    if (&li != this)
    {
        List<dataType> temp(li);
        std::swap(head, temp.head);
        std::swap(tail, temp.tail);
        std::swap(count, temp.count);
    }
    return *this;
}

template <class dataType>
Queue<dataType>::Queue(const dataType &data)
{
    enQueue(data);
}

template <class dataType>
void Queue<dataType>::enQueue(const dataType &data)
{
    addToTail(data);
}

Тогда вы можете делай так:

Queue<int> q;
q.enQueue(12345);
q.enQueue(67890);
q.printListForward();
...