怎么才能把 [] 运算符写成左值
  • 板块学术版
  • 楼主HaneDaniko
  • 当前回复4
  • 已保存回复4
  • 发布时间2024/7/13 17:59
  • 上次更新2024/7/13 19:34:43
查看原帖
怎么才能把 [] 运算符写成左值
1161172
HaneDaniko楼主2024/7/13 17:59

是这样的,正在封一个结构体,需要用到 operator []

但是如果像下面这么写的话会报错,因为这东西本质上只是个函数,没办法赋值

#include<bits/stdc++.h>
using namespace std;
struct hdk{
	int a[100];
	int operator [](int x){
		return a[x];
	}
}t;
int main(){
	t[1]=1;
}

但是如果返回地址的话确实能实现这种功能了,但是感觉有点丑

#include<bits/stdc++.h>
using namespace std;
struct hdk{
	int a[100];
	int* operator [](int x){
		return &a[x];
	}
}t;
int main(){
	*t[1]=1;
}

所以想问问有没有什么别的写法能不带这个解引用,比如像 STL 一样用迭代器实现之类的(btw,不会写迭代器,如果迭代器能实现上面要求的话,麻烦教我下怎么写)

2024/7/13 17:59
加载中...