Проблема с const * этой частью класса C ++ 2D Array - PullRequest
1 голос
/ 02 апреля 2011

Я работаю над 2d классом массива - и единственная часть, которая доставляет мне неприятности, это когда я объявляю константу Array2D.Оператор [] передает ссылку на & this конструктору Row.Когда я пытаюсь сделать это с константой 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
]

Хорошо, и вот код.Я знаю, что проблема связана с передачей * this указателя константы Array2D в конструктор Row, но я не могу найти решение этой проблемы.

Любая помощь будет принята с благодарностью.

//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);
}

1 Ответ

3 голосов
/ 02 апреля 2011

Просто измените спецификацию параметра, чтобы указать, что 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...