关于 [] 的重载

学术版

MornStar @ 2024-10-04 14:43:14

RT,结构体里有一个二维数组,想通过重载运算符做到 访问数组元素不需使用 name.arr[x][y] 而是 name[x][y]


by SClan_Official @ 2024-10-04 14:45:19

@MornStar operator[](size_t x) 返回结构体内的 arr[x]


by Crab_Tang @ 2024-10-04 15:12:07

@MornStar 什么类型的。


by rybp @ 2024-10-04 16:49:14

@MornStar 1 楼的那个说了跟没说一样。

给你贴一个我矩阵的实现吧:

class Mat {
private:
    int n, m;
public:
    int a[maxn][maxn];
    Mat () {}
    inline int* operator[] (int q) {
        return a[q];
    }
    inline const int* operator[] (int q) const {
        return a[q];
    }
};

by rybp @ 2024-10-04 16:50:18

注意这几个 const 不要动,一动就 CE。这是我扒自己三年前的代码扒下来的,后面好像优化了一版,找不到了故放弃。


by cqbzlym @ 2024-10-04 16:54:03

@rybp 哥啊你这代码是贺的我的吧。其实第二个 operator[] 可以不要,如果你后面成员函数都不带 const 限定符的话。


by rybp @ 2024-10-04 16:55:07

@Poncirus 若只吗,跟自己小号玩角色扮演还上瘾了你。滚回去做题。


by xxxxxzy @ 2024-10-04 17:23:16

@MornStar

struct matrix {
    int a[len][len];
    matrix() { mem(a);}
    matrix(vector<int> v) { rep(i, 0, len - 1) rep(j, 0, len - 1) a[i][j] = v[i * len + j]; }
    inline matrix operator*(matrix b) const {
        matrix c;
        rep(i, 0, len - 1) rep(j, 0, len - 1) rep(k, 0, len - 1) c[i][j] += a[i][k] * b[k][j] % mod;
        rep(i, 0, len - 1) rep(j, 0, len - 1) c[i][j] %= mod;
        return c;
    }
    inline int *operator[](int x) { return a[x]; }
    inline bool operator==(matrix &b) const {
        rep(i, 0, len - 1) rep(j, 0, len - 1) {
            if (a[i][j] != b[i][j]) return 0;
        }
        return 1;
    }
};

|