使用向量和指针

时间:2015-12-03 05:34:31

标签: c++ operator-overloading

我试图通过使用向量和指针来重载[] []。实际上,我成功编写了代码。但是我对矢量版本有点迷惑。请参考我的实现如下:

这是指针版本:

class Array2 {
    private:
    unsigned row, col;
    int** arr;
    public:
    Array2(unsigned r=0, unsigned c=0): row(r), col(c) {
        if(row * col != 0) {
            arr = new int*[row];
            for(int i = 0; i < row; i++) {
                arr[i] = new int[col];
            }
        }
    }

    class Proxy {
    public:
        Proxy(int* _array) : _array(_array) { }
        int& operator[](int index) {
            return _array[index];
        }
    private:
        int* _array;
    };

    Proxy operator [] (int index) {
        return Proxy(arr[index]);
    }
}

这是矢量版本:

class Array2 {
    private:
        unsigned row, col;
        vector<vector<int> > arr;
    public:
        Array2(unsigned r=0, unsigned c=0)
            : row(r), col(c), arr(r, vector<int>(c)) { }

    vector<int>& operator [] (int index) {
        return arr[index];
    }
}

这是失败矢量版本:

class Array2 {
    private:
        unsigned row, col;
        vector<vector<int> > arr;
    public:
        Array2(unsigned r=0, unsigned c=0)
            : row(r), col(c), arr(r, vector<int>(c)) { }

    class Proxy {
    public:
        Proxy(vector<int> _array) : _array(_array) { }

        int& operator[](int index) {
            return _array[index];
        }
    private:
        vector<int> _array;
    };

    Proxy operator [] (int index) {
        return Proxy(arr[index]);
    }
}

使用失败版本,我无法使用arr[2][3] = 23等操作成功为矢量赋值。谁能告诉我在失败矢量版本中我误解了什么?非常感谢。

1 个答案:

答案 0 :(得分:1)

复制Proxy(vector<int> _array) : _array(_array) { }时,vector。这意味着_array内的Proxy与原始vector无关(即arr[index]return Proxy(arr[index]);

您可以保存指向vector的指针。如:

class Proxy {
public:
    Proxy(vector<int>& _array) : p(&_array) {}
    int& operator[](int index) {
        return (*p)[index];
    }
private:
    vector<int>* p;
};

当然,你成功的矢量版本会更好。