欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 焦点 > C++设计模式+异常处理

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

2025/4/18 21:17:05 来源:https://blog.csdn.net/2301_77654321/article/details/147099998  浏览:    关键词:C++设计模式+异常处理

 

 

 

#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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词