重载后重载分配[] []

时间:2018-11-14 18:10:56

标签: c++

从C ++某些方面的修订开始,就已经成为对我有用的东西的草图。想法是将单个数组用作双精度数组,其中索引对用户是透明的。

class matrice {

    private:
        int* data;
        int rows, cols;
    public:
        matrice(int _rows, int _cols) : rows(_rows), cols(_cols) { data = new int[_rows*_cols]; std::cout << "matrice ctr" << std::endl;}
        // hardcoded 2x2 matrix
        void set_value() { data[0] = 1; data[1] = 0; data[3] = 1; data[4] = 0;}
        int get_rows() { return rows;}
        int get_cols() { return cols;}

        class proxy {
            private:
                int i;
                int j;
                const int rows; // it is constant so we don't mess up with the size of the matrix
                int *proxy_data;
            public:
                proxy(int* _proxy_data, int _i, const int& _rows) : proxy_data(_proxy_data), i(_i), rows(_rows) { }
                int operator[] (int _j) { j = _j; std::cout << "proxy:\n\tj = " << j << " " << proxy_data[j] << std::endl; return proxy_data[i*rows + j];}
        };

        proxy operator[] (int i) { std::cout << "matrice:\n\ti = " << i << std::endl; return proxy(data, i, rows); } 

};

int main()
{
    int rows = 2;
    int cols = 2;

    matrice matp(rows, cols);
    matp.set_value();
    matp[0][0] = 2;
    for (int i = 0;i < rows;i++) {
        for (int j = 0;j < cols;j++) {
            std::cout << "matp[" << i << "][" << j << "] = " << matp[i][j] << std::endl;
        }
    }
}

到目前为止,我可以访问数组中的数据,但是我想为其分配值,即:     matp [0] [0] = 2;

我该怎么办?

1 个答案:

答案 0 :(得分:1)

int& operator[] (int j)const&&

也删除int j成员是没有意义的。

int& operator[] (int j) const&& {
  std::cout << "proxy:\n\tj = " << j << " " << proxy_data[j] << std::endl; 
  return proxy_data[i*rows + j];}
};

或更好:

    template<class X>
    class proxy {
        private:
            X *proxy_data;
        public:
            proxy(X* _proxy_data, std::size_t i, std::size_t stride) : proxy_data(_proxy_data+i*stride) { }
            X& operator[] (std::size_t j) const&& { return proxy_data[j]; }
    };

使用proxy<int>proxy<const int>作为[][] const的返回值。