gpt4 book ai didi

c++ - const * C++ 2D Array 模板类的这一部分的问题

转载 作者:行者123 更新时间:2023-11-30 03:07:55 25 4
gpt4 key购买 nike

我正在研究二维数组类——唯一给我带来麻烦的部分是当我声明常量 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
]

好的,这是代码。我知道问题与将常量 Array2D 的 *this 指针传递给 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);
}

最佳答案

只需更改参数规范以反射(reflect)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)

关于c++ - const * C++ 2D Array 模板类的这一部分的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5520691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com