【C++深度剖析学习总结】 34 数组操作符的重载

【C++深度剖析学习总结】 34 数组操作符的重载

作者 CodeAllen ,转载请注明出处


1.问题
string类对象还具备C方式字符串的灵活性吗?还能直接访问单个字符吗?
绝对支持数组直接访问单个字符,使用操作符重载函数进行就可以

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

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

实验1 用C方式使用string类

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

运行结果:4

3.问题
类的对象怎么支持数组的下标访问?

4.重载数组访问操作符
被忽略的事实。。

  • 数组访问符是C/C++中的内置操作符
  • 数组访问符的原生意义是数组访问和指针运算—访问某个元素
C语言深度剖析:a[n] <–> *(a + n) <–> *(n + a) <–>n[a]

实验2 指针与数组的复习

#include <iostream>
#include <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;    // *(i+a)==>*(a+i)
                          //a[i] = i + 10;
    }
   
    for(int i=0; i<5; i++)
    {
        cout << *(i + a) << endl;  // cout << a[i] << endl;
    }
   
    return 0;
}

运行结果
0
1
2
3
4
10
11
12
13

数组访问操作符([])—原生意义—注意事项

  • 只能通过类的成员函数重载
  • 重载函数能且仅能使用一个参数
  • 可以定义不同参数的多个重载函数

实验3 重载数组访问操作符

#include<iostream>
#include<string>
using namespace std;
class Test
{
    int a[5];
public:
    int& operator [] (int i)//reference
    {
         return a[i];
    }
    //Operator overloading
    int& operator [] (const string& s)//reference
    {
        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.operator[](i) = i;
    }
    for (int i =0; i<t.length();i++)
    {
         cout<< t[i]<<endl;
    }
   
    cout << t["5th"] << endl;   //是可以实现字符串下表直接访问数组的,实现方式就是上边的code
    cout << t["4th"] << endl;
    cout << t["3rd"] << endl;
    cout << t["2nd"] << endl;
    cout << t["1st"] << endl;
    return 0;
}

运行结果
0
1
2
3
4
4
3
2
1
0

IntArray 数组类的完善
BCC编译器

小结
string类最大程度的兼容了C字符串的用法
数组访问符的重载能够使得对象模拟数组的行为
只能通过类的成员函数重载数组访问符
重载函数能且仅能使用一个参数

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章