C++筆記 第三十四課 陣列操作符的過載---狄泰學院
阿新 • • 發佈:2018-11-15
如果在閱讀過程中發現有錯誤,望評論指正,希望大家一起學習,一起進步。
學習C++編譯環境:Linux
第三十四課 陣列操作符的過載
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++;
}
}
34-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]
34-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
陣列訪問操作符([])—原生意義—注意事項
只能通過類的成員函式過載
過載函式能且僅能使用一個引數
可以定義不同引數的多個過載函式
34-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;
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字串的用法
陣列訪問符的過載能夠使得物件模擬陣列的行為
只能通過類的成員函式過載陣列訪問符
過載函式能且僅能使用一個引數