问题:
string类对象还具备C方式字符串的灵活性吗?还能直接访问单个字串符吗?
答案:是
字符串类的兼容性:
(1)string类最大限度的考虑了C字符串的兼容性
(2)可以按照C字符串的方式使用string对象
实例分析:用C方式使用string类
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s = "abcd1ef2g3";
int n = 0;
for(int i = 0; i < s.length(); i++)
{
if(isdigit(s[i]))
{
n++;
}
}
cout << n << endl;
return 0;
}
问题2:
类的对象怎么支持数组的下标访问?
答案:不支持,但是数组访问操作符的重载能够使得对象模拟数组的行为
重载数组访问操作符:
被忽略的实事。。。
数组访问符是c++中的内置操作符
数组访问符的原生意义是数组访问和指针运输
a[n] == *(a+n) == *(n+a) == n[a]
数组访问操作符([])
(1)只能通过类的成员函数重载
(2)重载函数能且仅能使用一个参数 (可以是不同的类型参数,看3)
(3)可以定义不同参数的多个重载函数
编程实验:重载数组访问操作符
#include <iostream>
#include <string>
using namespace std;
class Test
{
int a[5];
public:
/*int operator [] (int i)
{
return a[i]; //函数调用的返回值不能作为左值使用
}*/
int& operator [] (int i) //通过引用可以让函数调用出现在复赋值符号左边
{
return a[i];
}
int& operator [] (const string& s) //通过字符串访问一个数组
{
if(s == "1s")
{
return a[0];
}
if(s == "2s")
{
return a[1];
}
if(s == "3s")
{
return a[2];
}
if(s == "4s")
{
return a[3];
}
if(s == "5s")
{
return a[4];
}
}
int length()
{
return 5;
}
};
int main()
{
Test t;
for(int i = 0; i < t.length(); i++)
{
t[i] = i; //== t.operator [] (i) = i; 这里需要把i赋值给函数的返回值,但是通过引用可以让函数调用出现在复赋值符号左边
}
for(int i = 0; i < t.length(); i++)
{
cout<<t[i]<<endl;
}
cout << t["1s"] << endl;
cout << t["2s"] << endl;
cout << t["3s"] << endl;
cout << t["4s"] << endl;
cout << t["5s"] << endl;
return 0;
}