本文学习自 狄泰软件学院 唐佐林老师的 C++课程
实验1 :可以按照使用C字符串的方式使用 string 对象
实验2:数组访问操作符的重载
实验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++)
{
//检测字符是否是数字, s[i] 合法
if( isdigit(s[i]) )
{
n++;
}
}
cout << n << endl;
return 0;
}
mhr@ubuntu:~/work/c++$
mhr@ubuntu:~/work/c++$ g++ 34-1.cpp
mhr@ubuntu:~/work/c++$ ./a.out
4
mhr@ubuntu:~/work/c++$
在C/C++中 数组访问操作符的原生意义就是访问数组里里面的某个元素,他的深层意义是计算地址的偏移量。
实验2:数组访问操作符的重载
#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;
}
mhr@ubuntu:~/work/c++$
mhr@ubuntu:~/work/c++$ g++ 34-3.cpp
mhr@ubuntu:~/work/c++$ ./a.out
0
1
2
3
4
4
3
2
1
0
mhr@ubuntu:~/work/c++$