C++深度解析 数组操作符的重载 --- 数组访问操作符[ ](33)
通过数组访问操作符[ ],访问字符串里面的单个字符。
示例程序:
#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;
}
结果如下:

数组访问操作符[ ]
数组访问符是C/C++中的内置操作符。
数组访问符的原生意义是数组访问和指针运算。
a[n] <<==>> *(a+n) <<==>> *(n+a) <<==>>n[a]
示例程序:(指针与数组的复习)
#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++)
{
//a[i] = i + 10;
i[a] = i + 10; // 等价于:*(i + a) ==> *(a + i) ==> a[i]
}
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()
{
Test t;
for (int i = 0; i < t.length(); i++)
{
t[i] = 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;
}
结果如下:

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

2万+

被折叠的 条评论
为什么被折叠?



