Проблемы с шаблонами классов - PullRequest
0 голосов
/ 09 ноября 2019

, поэтому я работаю со связанным списком, и у меня есть все функции, которые работают, когда они работают с целыми числами. Я начал настраивать программу так, чтобы она следовала шаблону, чтобы он мог работать с другими заданными типами данных, такими как double, но это нарушило всю программу, и я не уверен, почему так, если вы знаете, почему это вызывает и как решитьэто было бы очень цениться.

#include <iostream>
#include "List.h"
using namespace std;
int main()
{
   List<int> linkedList;
   linkedList.insertByPos(0,16);
   linkedList.insertByPos(1,17);
   linkedList.insertByPos(2,18);
   linkedList.printList();

   linkedList.reverse();
   cout << endl;
   linkedList.printList();

   cout << "The position is " << linkedList.search(17) << endl;
   linkedList.insertByPos(3,19);
   linkedList.printList();
   linkedList.RemoveByPos(2);
   cout << endl;
   linkedList.printList();
    return 0;
}

#ifndef LIST_H
#define LIST_H
template <class T>
class List
{
private:
    struct Node
    {
        T data;
        Node* next;
    };
    Node* head;
    Node* curr;
    Node* temp;
public:
    List<T>();
    List(const List<T>& other);
    void printList();
    void reverse();
    int search(T value);
    void insertByPos(int pos, T value);
    void RemoveByPos(int pos);

};

#endif // LIST_H


#include "List.h"
#include <iostream>
using namespace std;
template <class T>
List<T>::List()
{
    head = nullptr;
    curr = nullptr;
    temp = nullptr;
}
template <class T>
List<T>::List(const List& other)
{
    cout << "copy constructor called:\n";
    if(other.head == nullptr) return;
    Node* dummyHead = new Node;
    curr = dummyHead;
    Node* othcurr = other.head;
    for(; othcurr!=nullptr; othcurr = othcurr->next)
    {
        curr->next = new Node;
        curr = curr->next;
        curr->data = othcurr->data;
        curr->next = nullptr;
    }
    head = dummyHead->next;
    delete dummyHead;
}
template <class T>
void List<T>::printList()
{
    curr = head;
    while(curr != nullptr)
    {
        cout << curr->data << endl;
        curr = curr->next;
    }
}
template <class T>
void List<T>::reverse()
{
    Node* next = nullptr;
     curr = head;
    while(curr != nullptr)
    {
        next = curr->next;
        curr->next = temp;
        temp = curr;
        curr = next;
    }
    head = temp;
    temp = nullptr;
}
template <class T>
int List<T>::search(T value)
{
    int counter = 0;
    curr = head;
    while(curr != nullptr && curr->data != value)
    {
        curr = curr->next;
        counter++;
    }
    if(curr == nullptr)
    {
        return -1;
    }
    return counter;
}
template <class T>
void List<T>::insertByPos(int pos, T value)
{
    curr = head;
    Node* n = new Node;
    n->data = value;
    int counter = 0;
    int bounds = 0;
    while(curr != nullptr)
    {
        bounds++;
        curr = curr->next;
    }
    if(bounds <= pos)
    {
       pos = bounds;
    }
    curr = head;
    while(counter != pos)
        {
            counter++;
            temp = curr;
            curr = curr->next;
        }
        n->next = curr;
                if(counter == 0)
                {
                    head = n;
                }
                else
                {
                    temp->next = n;
                }
    temp = nullptr;
}
template <class T>
void List<T>::RemoveByPos(int pos)
{
   Node* delPtr = nullptr;
   curr = head;
   temp = head;
   int counter = 0;
   int bounds;
     while(curr != nullptr)
    {
        bounds++;
        curr = curr->next;
    }
    if(pos >= bounds)
    {
        cout << "Bad pos value";
    }
    else
        {
                curr = head;
   while(counter != pos)
   {
       counter++;
       temp = curr;
       curr = curr->next;
   }
   delPtr = curr;
   curr = curr->next;
   temp->next = curr;
      if(counter == 0)
   {
       head = head->next;
       temp = nullptr;
   }


   delete delPtr;
        }

}

Ответы [ 2 ]

0 голосов
/ 09 ноября 2019

Есть множество проблем с шаблонами. Во-первых, когда вы вызываете связанный список, вы должны указать компилятору, какой тип T должен иметь. Например, написав

List<int> linkedList;

По той же причине вы должны изменить

List<T>::List(const List& other)
// to 
List<T>::List(const List<T>& other)

Кроме того, вы не можете (легко есть некоторые способы) поместить определения шаблонных функций в cppфайл. Вы должны поместить их в заголовочный файл. Подробнее читайте https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl Ваш код выдаст ошибку компоновщика после того, как вы заставите его скомпилироваться иначе.

0 голосов
/ 09 ноября 2019

Вам необходимо добавить «T» после «List»

List::List() void -> List<T>::List()

void List::printList() -> void List<T>::printList()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...