数组操作符的重载

本文探讨了C++ string类对象如何保持与C字符串的兼容性,包括直接访问单个字符,并详细介绍了如何重载数组访问操作符以模拟数组行为。通过实例展示了如何在类中实现这些特性,适合理解C++字符串操作和面向对象编程的高级技巧。
摘要由CSDN通过智能技术生成

问题:
string类对象还具备C方式字符串的灵活性吗?还能直接访问单个字串符吗?
答案:是

字符串类的兼容性:
(1)string类最大限度的考虑了C字符串的兼容性
(2)可以按照C字符串的方式使用string对象

实例分析:用C方式使用string类

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s = "abcd1ef2g3";
    int n = 0;

    for(int i = 0; i < s.length(); i++)
    {
        if(isdigit(s[i]))
        {
            n++;
        }
    }

    cout << n << endl;

    return 0;
}

问题2:
类的对象怎么支持数组的下标访问?
答案:不支持,但是数组访问操作符的重载能够使得对象模拟数组的行为

重载数组访问操作符:
被忽略的实事。。。
数组访问符是c++中的内置操作符
数组访问符的原生意义是数组访问和指针运输

a[n] == *(a+n)  ==  *(n+a) == n[a]

数组访问操作符([])
(1)只能通过类的成员函数重载
(2)重载函数能且仅能使用一个参数 (可以是不同的类型参数,看3)
(3)可以定义不同参数的多个重载函数

编程实验:重载数组访问操作符

#include <iostream>
#include <string>

using namespace std;

class Test
{
    int a[5];
public:
    /*int operator [] (int i)
    {
        return a[i];    //函数调用的返回值不能作为左值使用
    }*/

    int& operator [] (int i)    //通过引用可以让函数调用出现在复赋值符号左边
    {
        return a[i];
    }

    int& operator [] (const string& s)  //通过字符串访问一个数组
    {
        if(s == "1s")
        {
            return a[0];
        }
        if(s == "2s")
        {
            return a[1];
        }
        if(s == "3s")
        {
            return a[2];
        }
        if(s == "4s")
        {
            return a[3];
        }
        if(s == "5s")
        {
            return a[4];
        }
 
    }

    int length()
    {
        return 5;
    }
};

int main()
{
    Test t;

    for(int i = 0; i < t.length(); i++)
    {
        t[i] = i; //== t.operator [] (i) = i;  这里需要把i赋值给函数的返回值,但是通过引用可以让函数调用出现在复赋值符号左边
        
    }

    for(int i = 0; i < t.length(); i++)
    {
        cout<<t[i]<<endl;
    }
    
    cout << t["1s"] << endl;
    cout << t["2s"] << endl;
    cout << t["3s"] << endl;
    cout << t["4s"] << endl;
    cout << t["5s"] << endl;

    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值