1

在下面的课程中,当我尝试返回std::valarray&operator [] 说:invalid initialization of std::valarray& from R-Value reference std::valarray

我这样使用它:

int main()
{
    Matrix<int> MM(4, 4);
    for (int I = 0, K = 0; I < 4; ++I)
    {
        for (int J = 0; J < 4; ++J)
        {
            MM[I][J] = K++;  //Assigning to it does nothing atm :S
        }
    }

    for (int I = 0; I < 4; ++I)
    {
        for (int J = 0; J < 4; ++J)
        {
            std::cout<<MM[I][J]<<"  "; //Prints random values :l
        }
        std::cout<<"\n";
    }
}

课程如下:

template<typename T>
class Matrix
{
    private:
        int Width, Height;
        std::valarray<T> Elements;
        static_assert(std::is_arithmetic<T>::value, "Argument T must be of arithmetic type.");

    public:
        Matrix(int Width, int Height);
        Matrix(T* Data, int Width, int Height);
        Matrix(T** Data, int Width, int Height);


        std::valarray<T>& operator [](int Index);
        const std::valarray<T>& operator [](int Index) const;
};

template<typename T>
Matrix<T>::Matrix(int Width, int Height) : Width(Width), Height(Height), Elements(Width * Height, 0) {}

template<typename T>
Matrix<T>::Matrix(T* Data, int Width, int Height) : Width(Width), Height(Height), Elements(Width * Height)
{
    std::copy(Data, Data + (Width * Height), &Elements[0]);
}

template<typename T>
Matrix<T>::Matrix(T** Data, int Width, int Height) : Width(Width), Height(Height), Elements(Width * Height)
{
    std::copy(Data[0], Data[0] + (Width * Height), &Elements[0]);
}


//ERROR below..
template<typename T>
std::valarray<T>& Matrix<T>::operator [](int Index)
{
    return Elements[std::slice(Index * Width, Width, 1)];
}

template<typename T>
const std::valarray<T>& Matrix<T>::operator [](int Index) const
{
    return Elements[std::slice(Index * Width, Width, 1)];
}

所以我的问题是..如何重载 [] 运算符,以便我可以获得单行或单列,以便我可以索引并分配给它?我不想使用() subscript operator.

4

1 回答 1

2

在非const operator[]你有,这个表达

return Elements[std::slice(Index * Width, Width, 1)];

这将创建一个std::slice_array<T>对象,它是一个右值。您不能将此绑定到std::valarray<T>&. 可以通过将函数更改为按值返回 avalarray而不是按引用来修复该错误。

template<typename T>
std::valarray<T> Matrix<T>::operator [](int Index) // <-- return by value
{
    return Elements[std::slice(Index * Width, Width, 1)];
}
于 2013-06-09T04:02:07.920 回答