C++ 重载 [] 运算符

刚开始我是震惊的!

我从未想过\[\]下居然有逻辑!

从接触程序设计语言开始

曾因会使用a0访问数组元素而沾沾自喜

曾认为\[\] ,理应是访问数组的一种方式

曾认为\[\]只是一个无情的标识!

所以

当我们写下a0时,究竟是为了什么?

是为了找到a0对应的值

那么如何能找到它对应的值?

首先要找到它对应的地址

这样只是能读取

如何能修改其值?(a0=5)

当然是返回左值引用

重载\[\]运算符有何应用场景?

可以像数组一样访问链表类

代码逻辑是怎样的?

index=0 指针不动 返回其数据域

index=1 指针指向下个节点 返回其数据域

如何确保指针不出界?

最后一个节点的指针域是nullptr 如果指针指向nullptr则表示到头了

是否应该考虑const重载?

应该!

cpp 复制代码
#include <iostream>
#include <stdexcept>
 
template <typename T>
class LinkedList
{
private:
    struct Node
    {
        T data;     // 存储的数据
        Node *next; // 指向下一个节点的指针
 
        Node(T val, Node *ptr = nullptr) : data(val), next(ptr) {}
    };
 
    Node *head; // 链表的头节点
 
public:
    LinkedList() : head(nullptr) {}
    ~LinkedList()
    {
        clear();
    }
 
    void add(T value)
    {
        // 在链表末尾添加元素
        if (head == nullptr)
        {
            head = new Node(value);
        }
        else
        {
            Node *temp = head;
            while (temp->next != nullptr)
            {
                temp = temp->next;
            }
            temp->next = new Node(value);
        }
    }
 
    void clear()
    {
        // 清空链表,释放内存
        Node *current = head;
        while (current != nullptr)
        {
            Node *next = current->next;
            delete current;
            current = next;
        }
        head = nullptr;
    }
 
    T &operator[](int index)
    {
        // 重载[]运算符,以便可以使用索引访问元素
        Node *temp = head;
        int count = 0;
        while (temp != nullptr && count < index)
        {
            temp = temp->next;
            ++count;
        }
 
        if (temp == nullptr)
        {
            throw std::out_of_range("Index out of range");
        }
 
        return temp->data; // 返回对应节点的数据引用
    }
 
    // 为了避免在const对象上使用[]运算符时出错,添加const版本的[]运算符
    const T &operator[](int index) const
    {
        Node *temp = head;
        int count = 0;
        while (temp != nullptr && count < index)
        {
            temp = temp->next;
            ++count;
        }
 
        if (temp == nullptr)
        {
            throw std::out_of_range("Index out of range");
        }
 
        return temp->data;
    }
};
 
int main()
{
    LinkedList<int> list;
    list.add(10);
    list.add(20);
    list.add(30);
 
    // 访问和修改元素
    std::cout << list[1] << std::endl; // 20
    list[1] = 50;
    std::cout << list[1] << std::endl; // 50
 
    // 异常处理
    try
    {
        list[3]; // 0 1 2 没有 3
    }
    catch (const std::out_of_range &e)
    {
        std::cout << e.what() << std::endl;
    }
 
    return 0;
}
相关推荐
多加点辣也没关系6 小时前
JavaScript|第41章:性能优化实战
开发语言·javascript·性能优化
Resean02236 小时前
架构设计系列(十六):DDD 与代码架构
java·开发语言·架构
码途行者7 小时前
每天10分钟学Go:第22课 自定义错误
开发语言·后端·golang
23图7 小时前
C 语言开散列表(拉链法)拆解:链挂得没错,key=-1 会去读 T[-1]
c语言·开发语言·散列表
feixing_fx8 小时前
解构与展开:可读性和性能的取舍
开发语言·前端·javascript·前端框架
小飞在努力8 小时前
【实现负载均匀在线判题③】从零散模块到统一,编译运行全链路封装
c语言·开发语言·c++·笔记
饮水桶_T12 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
星恒随风12 小时前
从0实现C++ AI大模型接入SDK(四):大模型API接入、公共数据结构设计与日志库封装
linux·服务器·数据结构·c++·人工智能
炸膛坦客12 小时前
单片机/C/C++八股:(三十四)C 语言函数参数入栈顺序
c语言·开发语言·c++
咖啡八杯13 小时前
LoginUser 适配器模式:适配 SysUser 到 UserDetails
java·开发语言·后端·框架·适配器模式·若依