重载向量的多维数组运算符

问题描述 投票:0回答:1

嗨,我试图创建矩阵类,我想分配像矩阵[0][2]=3我检查了表格,发现一个解决方案与数组,但我想做与向量,不能理解为什么不工作?

 template<class T>
class Matrix
{
public:
    Matrix(int a, int b)
    {
        vector<vector<T> > vec( a , vector<T> (b, 0));
        matrixData = vec;
    }
    class Array1D
    {
    public:
        Array1D(vector<T> a):temp(a) {}
        T& operator[](int a)
        {
            return temp[a];
        }
        vector<T> temp;
    };

    vector<vector<T> > matrixData;
    Array1D operator[] (int a)
    {
        return Array1D(matrixData[a]);
    }
};

int main()
{
    Matrix<int> n(3,5);
    n[0][2] = 123; //assign

    cout<<n[0][2]; // wrong output getting 0
}
c++ operator-overloading
1个回答
2
投票

你必须改变 Array1D 实施到。

class Array1D
{
public:
    Array1D(vector<T>& a):temp(a) {}
    T& operator[](int a)
    {
        return temp[a];
    }
    vector<T>& temp;
};

如果没有这个,每次你调用 operator[] 矩阵上访问临时向量。因此,每次调用 n[0] 在不同的矢量上工作。所以之前的任何修改都不能保存,你总是看到的是 0 作为结果。

通过上述改变,您可以通过以下方式访问矩阵的原始向量 Array1D 代理类。

演示


1
投票

你正在返回错误的类型,从 Matrix::operator[]. 你需要通过引用来返回一个嵌套的向量,这样你就可以连锁下一个 [] 到它。

vector<T>& operator[] (int a)
{
   return matrixData[a];
}

事实上,你不需要内部... ... Array1D 类,因为 vector 已有 operator[]你可以把它完全删除。

这里是一个工作 演示.

© www.soinside.com 2019 - 2024. All rights reserved.