[英]How to declare operator/ overload function to operate on a const variable and a non-const variable?
[英]How to overload non-const index operator for valarray class
在下面的類中,當我嘗試為operator []
返回std::valarray&
,它說: 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
。
在非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)];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.