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