【问题标题】:Matrix class proxy for operator [] error运算符 [] 错误的矩阵类代理
【发布时间】:2016-04-14 04:03:28
【问题描述】:

所以,我有这样的课程:MatrixMatrix_Proxy。两者都应该检查范围是否有效,但在这里我省略了,因为这不是问题。

只要对象是非常量的,就可以了,但那不行。通过const&发送函数参数是有效的做法,所以这里失败了。

代码(简化):

#include <vector>
#include <cstdlib>
#include <iostream>

template <typename T>
class Matrix_Proxy
{
public:
    Matrix_Proxy(std::vector<T>& _ref, size_t _size) : ref(_ref), size(_size)
    {}
    T& operator[](int i)
    {
        return ref[i];
    }

    const T& operator[](int i) const
    {
        return ref[i];
    }

private:
    std::vector<T>& ref;
    size_t size;

};

template <typename T>
class Matrix
{
public:
    Matrix(size_t x) : values(x), size(x)
    {
        for(auto&& y : values)
        {
            y.resize(x);
            for(auto&& x : y)
                x = 0;
        }
    }

    Matrix_Proxy<T> operator [] (int i)
    {
        return Matrix_Proxy<T>(values[i],size);
    }

    const Matrix_Proxy<T> operator [] (int i) const
    {
        return Matrix_Proxy<T>(values[i],size);
    }

private:
    std::vector<std::vector<T>> values;
    size_t size;
};

int main()
{
    Matrix<int> intMat(5);                    //FINE
    std::cout << intMat[2][2] << std::endl;   //FINE

    const Matrix<int> cintMat(5);             //FINE
    std::cout << cintMat[2][2] << std::endl;  //ERROR

    _Exit(EXIT_SUCCESS);
}

错误:

no matching function for call to 'Matrix_Proxy<int>::Matrix_Proxy(const value_type&, const size_t&)'
         return Matrix_Proxy<T>(values[i],size);
                                              ^

有什么办法解决这个问题吗?

【问题讨论】:

    标签: c++ matrix operator-overloading stdvector


    【解决方案1】:

    问题的根本原因是您的代理允许非常量访问,即使代理本身是通过const 运算符生成的。换句话说,你的代码,如果它可以编译,将允许这样做:

    const Matrix<int> cintMat(5);
    cintMat[2][2] = 2; // Does not compile
    

    这是因为从operator [] const 生成的Matrix_Proxy 同时具有operator [] constoperator [] 非常量。您的Matrix_Proxy 不知道它是通过const 运算符生成的!

    要解决此问题,请引入另一个代理,并从const 运算符[] 返回:

    template <typename T>
    class Matrix_Proxy_Const
    {
    public:
        Matrix_Proxy_Const(const std::vector<T>& _ref, size_t _size) : ref(_ref), size(_size)
        {}
        const T& operator[](int i) const {
            return ref[i];
        }
    private:
        const std::vector<T>& ref;
        size_t size;
    };
    

    Matrix 类中更改const 运算符实现:

    const Matrix_Proxy_Const<T> operator [] (int i) const {
        return Matrix_Proxy_Const<T>(values[i],size);
    }
    

    Demo.

    【讨论】:

    • 哇,现在一切都完美了 :) 但我仍然归 std::vector 所有,但是,这无济于事。谢谢:)
    猜你喜欢
    • 2019-06-23
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 2020-04-03
    • 2019-04-16
    • 1970-01-01
    相关资源
    最近更新 更多