C++运算符重载(12) - 重载数组索引操作符[]

本篇主要讨论索引操作符 [] 的重载。
下面是关于重载[]的一些注意事项:
1) 当需要检测下标是否越界时,重载[]是很有用的。
2) 重载函数必须返回引用,因为类似的表达式“arr[i]”可以被当成一个左值。

下面程序演示了重载索引操作符[]

// 数组类的重载操作
#include<iostream>
#include<cstdlib>
using namespace std;

// 数组类
class Array {
private:
    int* ptr;
    int size;
public:
    Array(int*, int);
    // 重载[]操作符,使得可以像数组一样访问这个类
    int& operator[] (int);
    void print() const;
};

// []操作符的重载实现。这个函数必须返回引用,且不能为const,因为可能会用作左值。例如arr[] = xxx;
int& Array::operator[](int index) {
    if (index >= size) {
        cout << "Array index out of bound, exiting";
        exit(0);
    }
    return ptr[index];
}

// 构造函数
Array::Array(int* p = NULL, int s = 0) {
    size = s;
    ptr = NULL;
    if (s != 0) {
        ptr = new int[s];
        for (int i = 0; i < s; i++)
            ptr[i] = p[i];
    }
}

void Array::print() const {
    for (int i = 0; i < size; i++)
        cout << ptr[i] << " ";
    cout << endl;
}

int main() {
    int a[] = { 1, 2, 4, 5 };
    Array arr1(a, 4);
    arr1[2] = 6;
    arr1.print();
    arr1[8] = 6;
    return 0;
}

运行结果:
1 2 6 5
Array index out of bound, exiting

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C++运算符重载是一种特性,允许我们重新定义已有的运算符的行为,使其适用于自定义的数据类型。差集运算符(-)也可以进行重载。 差集运算符用于计算两个集合之间的差异,即从一个集合中去除另一个集合中存在的元素。在C++中,我们可以通过重载差集运算符来实现集合类的差集操作。 下面是一个示例代码,演示了如何重载差集运算符: ```cpp #include <iostream> #include <set> class Set { private: std::set<int> elements; public: Set() {} Set(std::initializer_list<int> initList) { for (int element : initList) { elements.insert(element); } } Set operator-(const Set& other) const { Set difference; for (int element : elements) { if (other.elements.find(element) == other.elements.end()) { difference.elements.insert(element); } } return difference; } void print() const { for (int element : elements) { std::cout << element << " "; } std::cout << std::endl; } }; int main() { Set set1 = {1, 2, 3, 4, 5}; Set set2 = {3, 4, 5, 6, 7}; Set difference = set1 - set2; difference.print(); // 输出: 1 2 return 0; } ``` 在上面的示例中,我们定义了一个名为Set的类,表示一个集合。通过重载差集运算符(operator-),我们可以使用减号操作符来计算两个Set对象之间的差集。在重载函数中,我们遍历第一个集合的元素,并检查它们是否存在于第二个集合中。如果不存在,则将其添加到差集中。 相关问题: 1. 什么是运算符重载? 2. 如何重载其他运算符? 3. 运算符重载有什么注意事项?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值