C++重载——字符串类的实现

本文参照于狄泰软件学院,唐佐林老师的——《C++深度剖析教程》

我们知道C语言的字符串是用字符数组来实现的。这就意味着我们可以用下标操作符[]来访问字符串中的单个字符。
那么,string类可以直接访问单个字符吗?

用C方式使用string类

示例代码:用C方式使用string类

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{

    string s = "a2b2c3d4e";
    int n = 0;

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

    cout << n << endl;

    return 0;
}

输出结果:4

从结果来看,我们可以安装C字符串的方式来使用string对象。

问题:string类是怎么支持数组的下标访问的?

数组访问符实际是C/C++中的内置操作符,既然是操作符,我们可以进行操作符重载来支持string类的下标访问。
首先,我们要知道,数组下标是如何访问到数组的具体位置的。
在C语言中,我们可以通过指针运算来访问具体数组位置上的元素。

*(a + i) –> a[i]
*(i + a) –> a[i]

实际上,数组下标和指针运算时这样转换的:

a[n] <–> (a+n) <–> (n+a) <–> n[a]

数组下标就是通过指针算偏移量,得出元素位置。

重载数组访问操作符

  1. 只能通过类的成员函数重载
  2. 重载函数只能使用一个参数
  3. 可以定义不同参数的多个重载函数

示例代码

#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;
}

(1) 函数的返回值不能为左值,如果希望返回值为左值,那就必须返回引用类型。
(2) 操作符重载函数也符合重载函数规则,可以定义多个同名函数。

猜你喜欢

转载自blog.csdn.net/small_prince_/article/details/80518928
今日推荐