[]运算符重载

为什么要重载[]

在这里插入图片描述

因为自定义数据类型数组进行[]方式访问,会报错,因为编译器不知道该如何访问,需要对[]进行重载才可以

重载[]运算符

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

在这里插入图片描述
在这里插入图片描述

如何才能进行修改的操作呢?

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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_53157173/article/details/114974892