首页 > 解决方案 > 通用单链表,无可行重载 =

问题描述

我第一次创建一个通用的单链表。我有这个错误指出:

No viable overloaded '='

所以我决定重载 '=' 运算符以使其工作,但我仍然收到相同的错误,我不知道为什么。这是我的头文件:

#ifndef LinkedList_hpp
#define LinkedList_hpp

#include <iostream>

template<class T>
struct Node {
    T data;
    Node<T>* next;
};

template<class T>
class SingleLinkedList {
private:
    Node<T>* head, tail;

    SingleLinkedList & operator=(const SingleLinkedList &rhs) {
        head = rhs.head;
        tail = rhs.tail;
        return *this;
    }
public:
    SingleLinkedList() {
        head = nullptr;
        tail = nullptr;
    }

    void createNode(const T& theData) {
        Node<T>* temp = new Node<T>;
        temp->data = theData;
        temp->next = nullptr;
        if(head == nullptr) {
            head = temp;
            tail = temp;
            temp = nullptr;
        }
        else {
            tail->next = temp;
            tail = temp;
        }
    }

    void display() {
        Node<T>* temp = new Node<T>;
        temp = head;
        while(temp != nullptr) {
            std::cout << temp->data << "\t";
            temp = temp->next;
        }
    }

    void insert_start(const T& theData) {
        Node<T>* temp = new Node<T>;
        temp->data = theData;
        temp->next = head;
        head = temp;
    }

    void insert_position(int pos, const T& theData) {
        Node<T>* previous = new Node<T>;
        Node<T>* current = new Node<T>;
        Node<T>* temp = new Node<T>;
        temp = head;
        for(int i  = 1; i < pos; i++) {
            previous = current;
            current = current->next;

        }
        temp->data = theData;
        previous->next = temp;
        temp->next = current;
    }

    void delete_first() {
        Node<T>* temp = new Node<T>;
        temp = head;
        head = head->next;
        delete temp;
    }

    void delete_last() {
        Node<T>* previous = new Node<T>;
        Node<T>* current = new Node<T>;
        current = head;
        while(current->next != nullptr) {
            previous = current;
            current = current->next;
        }
        tail = previous;
        previous->next = nullptr;
        delete current;
    }

    void delete_position(int pos) {
        Node<T>* previous = new Node<T>;
        Node<T>* current = new Node<T>;
        current = head;
        for(int i = 1; i < pos; i++) {
            previous = current;
            current = current->next;
        }
        previous->next = current->next;
    }

    Node<T>* search(Node<T>* head, const T& target) {

    }
};

我应该在结构节点中创建一个赋值运算符吗?我不确定还能尝试什么。

这是我收到错误的地方:

在此处输入图像描述

标签: c++xcodelinked-listoperator-overloading

解决方案


推荐阅读