C++设计模式+异常处理

发布于:2025-04-12 ⋅ 阅读:(38) ⋅ 点赞:(0)

 

 

 

#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>
#include <stdexcept>  // 包含异常类

using namespace std;

// 该作业要求各位写一个链表
// 所以myList类里面需要一个真正的链表

template <class T>
class myList{
public:
    struct Node{
        // 数据域
        T val;
        // 指针域
        Node* next;
        Node* prev;
    };

    // 迭代器
    class iterator{
    public:
        Node* cur;  // head地址
        iterator(Node* node = nullptr) 
        : cur(node) {}

        T& operator*() {
            return cur->val;
        }

        iterator& operator++() {  // 前缀 ++
            if (cur) 
                cur = cur->next;
            return *this;
        }

        iterator& operator++(int) {  // 后缀 ++
            if (cur) 
                cur = cur->next;
            return *this;
        }

        bool operator!=(const iterator& other) const {
            return cur != other.cur;
        }
    };

    myList();
    void push_back(const T& val);
    myList& operator<<(const T& val);
    T& operator[](int index);
    int size();

    iterator begin() {
        return iterator(head->next);
    }

    iterator end() {
        return iterator(NULL);
    }

private:
    Node* head;  // 真正的链表(链表头头节点)
    Node* tail;  // 链表尾节点
    int count;   // 元素数量
};

template <typename T>
myList<T>::myList(){
    head = new Node;
    head->next = NULL;
    head->prev = NULL;
    tail = head;  // 只有头节点的情况下,尾节点即使是头节点
    count = 0;
}

template <typename T>
void myList<T>::push_back(const T& val){
    Node* newnode = new Node;
    newnode->val = val;
    newnode->next = NULL;
    newnode->prev = tail;

    tail->next = newnode;

    tail = newnode;
    count++;
}

template <typename T>
myList<T>& myList<T>::operator<<(const T& val){
    push_back(val);
    return *this;
}

template <typename T>
T& myList<T>::operator[](int index){
    if (index < 0 || index >= count) {
        throw std::out_of_range("超出范围");  // 如果索引超出范围,抛出异常
    }
    Node* p = head->next;
    for (int i = 0; i < index; i++) {
        p = p->next;
    }
    return p->val;
}

template <typename T>
int myList<T>::size(){
    return count;
}

int main(int argc, const char** argv){
    try {
        myList<int> l;
        l << 1 << 3 << 5 << 7 << 9;  // 插入5个数

        // 输出链表的元素
        myList<int>::iterator it = l.begin();
        for (it; it != l.end(); ++it) {
            cout << *it << endl;
        }

        // 尝试访问链表中的第六个元素,应该抛出异常
        cout << l[5] << endl;  // 此行会抛出异常

    } catch (const std::out_of_range& e) {
        cout <<e.what() << endl;  // 捕获并输出异常信息
    }

    return 0;
}