数组操作符的重载

String类最大限度的考虑了C字符串的兼容性,可以按照使用C字符串的方式使用string对象,也就是可以通过数组下标访问String对象的单个字符,例子

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
  string s = "abcdefg123";
  int n = 0;
  for(int i=0;i<s.length();i++)
  {
      if(isalpha(s[i]))
      {
         n++;
      }
  }
  cout<<n<<endl;
}

结果:

sice@sice:~$ ./a.out 
7

那么类的对象是怎么支持数组的下标访问的呢?这是大家常常忽略的事实,数组访问符设是C/C++中的内置操作符,也就是可以算出偏移量,数组访问符的原生意义是数组访问和指针运算,这里我们就开始引入数组操作符的重载
数组访问操作符([])
只能通过类的成员函数重载
重载函数能且仅能使用一个参数
可以定义不同参数的多个重载函数

例子:

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int a[5];
public:
    int& operator [] (int i)
    {
        return a[i];
    }
    
    int& operator [] (const string& s)
    {
        if( s == "1st" )
        {
            return a[0];
        }
        else if( s == "2nd" )
        {
            return a[1];
        }
        else if( s == "3rd" )
        {
            return a[2];
        }
        else if( s == "4th" )
        {
            return a[3];
        }
        else if( s == "5th" )
        {
            return a[4];
        }
        
        return a[0];
    }
    
    int length()
    {
        return 5;
    }
};

int main()
{
    Test t;
    
    for(int i=0; i<t.length(); i++)
    {
        t[i] = i;
    }
    
    for(int i=0; i<t.length(); i++)
    {
        cout << t[i] << endl;
    }
    
    cout << t["5th"] << endl;
    cout << t["4th"] << endl;
    cout << t["3rd"] << endl;
    cout << t["2nd"] << endl;
    cout << t["1st"] << endl;
    
    return 0;
}

结果:

sice@sice:~$ ./a.out 
0
1
2
3
4
4
3
2
1
0

可以看出数组操作符重载了,到这里大家就不会觉得通过数组下标访问字符串觉得奇怪了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值