---- 整理自狄泰软件唐佐林老师课程
1. 问题一
string类对象具备C方式字符串的灵活性吗?还能直接访问单个字符吗?
1.1 字符串类的兼容性
- string类最大限度的考虑了C字符串的兼容性
- 可以按照使用C字符串的方式使用string对象

1.2 编程实验:用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;
}

2. 问题二
类的对象怎么支持数组的下标访问?

2.1 重载数组访问操作符
- 数组访问符是C/C++中的内置操作符
- 数组访问符的原生意义是数组访问和指针运算

2.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; // a[i] = i + 10;
}
for(int i=0; i<5; i++)
{
cout << *(i + a) << endl; // cout << a[i] << endl;
}
return 0;
}

2.3 数组访问操作符 [ ]
- 只能通过类的成员函数重载
- 重载函数能且只能使用一个参数
- 可以定义不同参数的多个重载函数
2.4 编程实验:重载数组访问操作符

注解:事实上在执行 return 语句时系统是在内部自动创建了一个临时变量,然后将return要返回的那个值赋给这个临时变量。所以当被调函数运行结束后return后面的返回值就被释放掉了,最后是通过这个临时变量将值返回给主调函数的。而且定义函数时指定的返回值类型实际上指定的就是这个临时变量的类型。这些都是系统自动完成的,了解即可。
用引用解决上述函数调用的返回值不能作为左值使用的问题:

注解:在一个类中,
函数返回 “值类型”:在执行 =(赋值)时,在内存中会出现 临时变量,由临时变量执行 =(赋值操作)。
函数返回 “引用类型”:在执行 =(赋值)时,而不会出现临时变量情况,只对数据进行了拷贝。

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

![BUUCTF Reverse/[GWCTF 2019]re3](https://img-blog.csdnimg.cn/401438f5b88a4f109a568d4e1bd0db92.png)

















](https://img-blog.csdnimg.cn/1341561e304e4701ba6a4f0d79c0121f.png)
