📌  相关文章
📜  链表类中的运算符重载'<<‘和’>>’运算符(1)

📅  最后修改于: 2023-12-03 14:58:14.175000             🧑  作者: Mango

链表类中的运算符重载

在 C++ 中,我们可以通过运算符重载来改变类对象之间的操作行为。链表是一种常见的数据结构,我们可以通过重载运算符来使链表类对 <<>> 运算符进行操作。

1. 运算符重载简介

运算符重载是一种特殊的函数重载,通过定义适当的运算符函数来改变运算符的操作行为。运算符重载的一般方法是使用关键字 operator 后跟要重载的运算符。

例如,要重载链表类中的 <<>> 运算符,我们可以定义两个运算符函数 operator<<operator>>

2. 重载运算符 <<

重载运算符 << 使我们可以方便地以一种可读的方式打印链表的内容。下面是一个链表类重载运算符 << 的示例:

#include <iostream>

class Node {
public:
    int data;
    Node* next;

    Node(int data) {
        this->data = data;
        this->next = nullptr;
    }
};

class LinkedList {
private:
    Node* head;

public:
    LinkedList() {
        head = nullptr;
    }

    void insert(int data) {
        Node* newNode = new Node(data);
        if (head == nullptr) {
            head = newNode;
        } else {
            Node* current = head;
            while (current->next != nullptr) {
                current = current->next;
            }
            current->next = newNode;
        }
    }

    friend std::ostream& operator<<(std::ostream& os, const LinkedList& list) {
        Node* current = list.head;
        while (current != nullptr) {
            os << current->data << " ";
            current = current->next;
        }
        return os;
    }
};

int main() {
    LinkedList list;
    list.insert(1);
    list.insert(2);
    list.insert(3);

    std::cout << list;  // 使用重载的 << 运算符打印链表内容

    return 0;
}

上述示例中,我们在 LinkedList 类中定义了一个友元函数 operator<< 来重载 << 运算符。该函数遍历链表,并将节点的数据打印到输出流中。

3. 重载运算符 >>

重载运算符 >> 使我们可以方便地向链表中插入元素。下面是一个链表类重载运算符 >> 的示例:

#include <iostream>

class Node {
public:
    int data;
    Node* next;

    Node(int data) {
        this->data = data;
        this->next = nullptr;
    }
};

class LinkedList {
private:
    Node* head;

public:
    LinkedList() {
        head = nullptr;
    }

    void insert(int data) {
        Node* newNode = new Node(data);
        if (head == nullptr) {
            head = newNode;
        } else {
            Node* current = head;
            while (current->next != nullptr) {
                current = current->next;
            }
            current->next = newNode;
        }
    }

    friend std::istream& operator>>(std::istream& is, LinkedList& list) {
        int data;
        is >> data;
        list.insert(data);
        return is;
    }
};

int main() {
    LinkedList list;
    std::cout << "Enter elements (enter -1 to stop): ";
    std::cin >> list >> list >> list;  // 使用重载的 >> 运算符插入数据

    Node* current = list.head;
    while (current != nullptr) {
        std::cout << current->data << " ";
        current = current->next;
    }

    return 0;
}

上述示例中,我们在 LinkedList 类中定义了一个友元函数 operator>> 来重载 >> 运算符。该函数从输入流中读取数据,并将数据插入到链表中。

总结

通过运算符重载,我们可以使链表类更加方便地使用 <<>> 运算符。这样可以使链表的打印和插入操作更加简洁和易读。