运算符 [][] 重载 - 更改值

Operator[][] overload - to change the value

本文关键字:重载 运算符      更新时间:2023-10-16

我有一个matrix类,希望执行此操作:

matrix m1(2,4);     //creates matrix of size 2,4 full of 1's
m1[1][2]=4;         //I wish the value in place m1- row 1 col 2 will be 4

这是我的代码是如何编写的示例(在这个网站上找到 ty 塞斯·卡内基!!

class matrix{
public:
    matrix() {
        _arrayofarrays = new int*[10];
        for(int i = 0; i < 10; ++i)
            _arrayofarrays[i] = new int[10];
    }
    class Proxy {
    public:
        Proxy(int* _array) : _array(_array) { }
        int operator[](int index) {
            return _array[index];
        }
    private:
        int* _array;
    };
    Proxy operator[](int index) {
        return Proxy(_arrayofarrays[index]);
    }
private:
    int** _arrayofarrays;
};

问题是:m1[2][4] 返回一个 int 和 offcorce,如果我选择返回的值,它不会改变 m1 值

我该怎么做才能更改值?(也许返回 int>' 什么的?)

返回int&而不是int