1 C++中数组访问操作符的重载
1.1 重载数组访问操作符
对于数组操作符:
- 数组操作符是C/C++中的内置操作符。
- 数组访问符的原生意义是数组访问和指针运算。
数组访问操作符([]):
- 只能通过类的成员函数重载。
- 重载函数能且仅能使用一个参数。
- 可以定义不同参数的多个重载函数。
数组访问符的重载能够使得对象数组模拟数组的行为。
重载数组访问操作符:
#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;
}
2 重载数组访问操作符时出现的问题
对于如下代码在VS中和g++中都可以编译通过,但是运行的时候就会出现由于访问了0地址而出错。
#include <iostream>
#include <string>
using namespace std;
class Demo30
{
private:
int val[4];
public:
Demo30()
{
val[0] = 0;
val[1] = 1;
val[2] = 2;
val[3] = 3;
}
int operator [] (int index)
{
if ((0 <= index) && (index < 4))
{
return val[index];
}
return -1;
}
int operator [] (string index) const // 这里返回值必须为int,否则无法复现错误
{
if (index == "0")
{
return val[0];
}
else if (index == "1")
{
return val[1];
}
else if (index == "2")
{
return val[2];
}
else if (index == "3")
{
return val[3];
}
else
{
return -1;
}
}
};
int main()
{
const Demo30 demo;
cout << demo[0] << endl; //这里下标必须为0,否则编译错误
return 0;
}
这是编译器的bug吗?先把问题挂在这里。
参考资料: