在下面的课程中,当我尝试为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
。
答案 0 :(得分:1)
在您所拥有的非const
operator[]
中,此表达式
return Elements[std::slice(Index * Width, Width, 1)];
这会创建一个std::slice_array<T>
对象,它是一个右值。您无法将其绑定到std::valarray<T>&
。可以通过更改函数来修复错误,以按值而不是按引用返回valarray
。
template<typename T>
std::valarray<T> Matrix<T>::operator [](int Index) // <-- return by value
{
return Elements[std::slice(Index * Width, Width, 1)];
}