34-数组操作符的重载

34-数组操作符的重载

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

字符串类的兼容性

  • string类最大限度的考虑了C字符串的兼容性
  • 可以按照使用C字符串的方式使用string对象
string s = "a1b2c3d4e";
int n = 0;

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

【范例代码】用C方式使用字符串

#include <iostream>
#include <string>

using namespace std;

int main(int argc, const char* argv[]) {
    string s = "a1b2c3d4e";
    int n = 0;

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

    cout << n << endl;

    return 0;
}
【问题】类的对象怎么支持数组的下标访问?

重载数组访问操作符

被忽略的事实:

  • 数组访问符是C/C++中的内置操作符
  • 数组访问符的原生意义是数组访问和指针运算
a[n] <--> *(a + n) <--> *(n + a) <--> n[a]

【范例代码】指针与数组的复习

#include <iostream>
#include <string>

using namespace std;

int main(int argc, const char* argv[]) {
    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;
}
数组访问操作符([ ]):
  • 只能通过类的成员函数重载
  • 重载函数能且仅能使用一个参数
  • 可以定义不同参数的多个重载函数

【范例代码】重载数组访问操作符

#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(int argc, const char* argv[]) {
    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;
}

猜你喜欢

转载自blog.csdn.net/qq_19247455/article/details/80332502