在下面的课程中,当我尝试返回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
.