为什么要重载[]
因为自定义数据类型数组进行[]方式访问,会报错,因为编译器不知道该如何访问,需要对[]进行重载才可以
重载[]运算符
代码语言:javascript复制#include<iostream>
using namespace std;
class wood {
public:
int *num;
int operator[](int index)
{
return this->num[index];
}
};
void test()
{
wood d;
d.num = new int[3];
d.num[0] = 0;
d.num[2] = 2;
d.num[1] = 1;
int num=d[0];
cout << num << endl;
cout << d[2] << endl;
}
int main()
{
test();
return 0;
}
如何才能进行修改的操作呢?
代码语言:javascript复制#include<iostream>
using namespace std;
class wood {
public:
int *num;
int& operator[](int index)
{
return this->num[index];
}
};
void test()
{
wood d;
d.num = new int[3];
d.num[0] = 0;
d.num[2] = 2;
d.num[1] = 1;
//d[0] = 100;
d.operator[](100);
int num=d[0];
cout << num << endl;
cout << d[2] << endl;
}
int main()
{
test();
return 0;
}