【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字符串的用法
數組訪問符的重載能夠使得對象模擬數組的行爲
只能通過類的成員函數重載數組訪問符
重載函數能且僅能使用一個參數