第34课.数组操作符的重载("[]"重载)

时间:2024-04-15 06:53:55

1.问题:string类对象还具备c方式字符串的灵活性吗?还能直接访问单个字符吗?

答案:可以按照c字符串的方式使用string对象

string s = "a1b2c3d4e";
int n = 0; for(int i = 0; i < s.length(); i++)
{
if(isdigit(s[i]))
{
n++;
}
}

2.类的对象怎么支持数组的下表访问?(string类对象可以直接使用)

答:c++编译器并不认可将数组访问操作符和任意的类对象任意使用

被忽略的事实:

a.数组访问符([])是c/c++中的内置操作符(和+,-,*,/一样的操作符)

d.数组访问符的原生意义是数组访问和指针运算

3.重载数组访问操作符([])

a.只能通过类的成员函数重载(与=一样)

b.重载函数能且仅能使用一个参数

c.可以定义不同的多个重载函数

eg:

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

第34课.数组操作符的重载("[]"重载)