C++中数组操作符的重载

字符串类的兼容性


  • 存在的一些历史遗留问题

    • C语言不支持真正意义上的字符串
    • C语言用字符数组和一组函数实现字符串操作
    • C语言不支持自定义类型,因为无法获取字符串类型
    • C++语言直接支持C语言的所有概念
    • C++语言中没有原生的字符串类型
  • C++标准提供了字符串类(string类)

    • string直接支持字符串连接
    • string直接支持字符串的大小比较
    • string直接支持子串查找和提取
    • string直接支持字符串的插入和替换
  • string类最大限度的考虑了C字符串的兼容性

  • 可以按照使用C字符串的方式使用string对象

using namespace std;

int main()
{
    int a[5] = {0};
    
    for(int i=0; i<5; i++)
    {
        a[i] = i;
    }
    
    for(int i=0; i<5; i++)
    {
        cout << *(a + i) << endl;    // cout << a[i] << endl;
    }
    
    cout << endl;
    
    for(int i=0; i<5; i++)
    {
        i[a] = i + 10;    // a[i] = i + 10;
    }
    
    for(int i=0; i<5; i++)
    {
        cout << *(i + a) << endl;  // cout << a[i] << endl;
    }
    
    return 0;
}
  • 这里一定要清楚:
    • 数组访问符是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;
}

小结


  • string类最大程度的兼容了C字符串的用法
  • 数组访问符的重载能够使得对象模拟数组的行为
  • 只能通过类的成员函数重载数组访问符
  • 重载函数能且仅能使用一个参数
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容