[英]Problem with const *this portion of a C++ 2D Array templated class
I'm working on a 2d array class -- and the only portion that is giving me trouble is when I declare a constant Array2D. 我正在研究2d数组类-唯一给我带来麻烦的部分是当我声明常量Array2D时。 The [] operator passes a reference to &this to the Row constructor.
[]运算符将对&this的引用传递给Row构造函数。 When I try to do this with a constant Array2D, I'm given the following error message:
当我尝试使用常量Array2D执行此操作时,出现以下错误消息:
error C2665: 'Row<T>::Row' : none of the 2 overloads could convert all the argument types
with
[
T=int
]
row.h(14): could be 'Row<T>::Row(Array2D<T> &,int)'
with
[
T=int
]
while trying to match the argument list '(const Array2D<T>, int)'
with
[
T=int
]
array2d.h(87) : while compiling class template member function 'Row<T> Array2D<T>::operator [](int) const'
with
[
T=int
]
main.cpp(30) : see reference to class template instantiation 'Array2D<T>' being compiled
with
[
T=int
]
row.h(34): error C2662: 'Array2D<T>::Select' : cannot convert 'this' pointer from 'const Array2D<T>' to 'Array2D<T> &'
with
T=int Conversion loses qualifiers
\row.h(33) : while compiling class template member function 'int &Row<T>::operator [](int)'
with
T=int
main.cpp(35) : see reference to class template instantiation 'Row<T>' being compiled
with
[
T=int
]
Okay, and here's the code. 好的,这是代码。 I know the problem has to do with passing the *this pointer of the constant Array2D to the Row constructor, but I can't for the life of me figure out the solution.
我知道问题与将常量Array2D的* this指针传递给Row构造函数有关,但是我一生都无法找出解决方案。
Any help would be greatly appreciated. 任何帮助将不胜感激。
//from array2d.h
template <typename T>
Row<T> Array2D<T>::operator[](int row) const
{
if(row >= m_rows)
throw MPexception("Row out of bounds");
return Row<T>(*this , row);
}
//from row.h
template <typename T>
class Row
{
public:
Row(Array2D<T> & array, int row);
T operator [](int column) const;
T & operator [](int column);
private:
Array2D<T> & m_array2D;
int m_row;
};
template <typename T>
Row<T>::Row(Array2D<T> & array, int row) : m_row(row), m_array2D(array)
{}
template <typename T>
T Row<T>::operator[](int column) const
{
return m_array2D.Select(m_row, column);
}
template <typename T>
T & Row<T>::operator[](int column)
{
return m_array2D.Select(m_row, column);
}
Simply change the parameter specification to reflect that Row
will not change m_array
: 只需更改参数说明以反映
Row
不会更改m_array
:
Row(Array2D<T> const & array, int row); // argument is read-only
… ...
Row<T>::Row(Array2D<T> const & array, int row) : m_row(row), m_array2D(array)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.