重载操作符[]

代码

复制代码
#include <iostream>
using namespace std;

template<int Size>
class Index
{
    public:
        int operator[](char vchar) 
        { return vchar % Size; }
};

int main()
{
    Index<26> index;
    cout << index['a'] << endl;
}
复制代码

结果

19

注意

模版分类型模版(函数模版、类模版)和非类型模版,这里是非类型模版,在使用时注意在<>声明此参数





本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3601416.html,如需转载请自行联系原作者

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python中的重载操作符指的是通过定义类的特殊方法,使得该类的对象可以支持相应的操作符。以下是一些常用的重载操作符及其对应的特殊方法: - 加法操作符: `+`,特殊方法名为 `__add__(self, other)`。 - 减法操作符: `-`,特殊方法名为 `__sub__(self, other)`。 - 乘法操作符: `*`,特殊方法名为 `__mul__(self, other)`。 - 除法操作符: `/`,特殊方法名为 `__truediv__(self, other)`。 - 取模操作符: `%`,特殊方法名为 `__mod__(self, other)`。 - 按位与操作符: `&`,特殊方法名为 `__and__(self, other)`。 - 按位或操作符: `|`,特殊方法名为 `__or__(self, other)`。 - 按位异或操作符: `^`,特殊方法名为 `__xor__(self, other)`。 - 左移操作符: `<<`,特殊方法名为 `__lshift__(self, other)`。 - 右移操作符: `>>`,特殊方法名为 `__rshift__(self, other)`。 - 一元加操作符: `+`,特殊方法名为 `__pos__(self)`。 - 一元减操作符: `-`,特殊方法名为 `__neg__(self)`。 - 一元取反操作符: `~`,特殊方法名为 `__invert__(self)`。 - 小于操作符: `<`,特殊方法名为 `__lt__(self, other)`。 - 小于等于操作符: `<=`,特殊方法名为 `__le__(self, other)`。 - 等于操作符: `==`,特殊方法名为 `__eq__(self, other)`。 - 大于等于操作符: `>=`,特殊方法名为 `__ge__(self, other)`。 - 大于操作符: `>`,特殊方法名为 `__gt__(self, other)`。 通过定义这些特殊方法,我们可以自定义类的行为,使其支持与内置类型相同的操作符
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值