2011-04-02 89 views
1

我正在研究一个2d数组类 - 唯一给我带来麻烦的部分是当我声明一个常量Array2D。 []运算符将对&的引用传递给Row构造函数。当我尝试用恒定Array2D要做到这一点,我给出以下错误消息:问题const * C++二维数组模板类的这一部分


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的这个指针传递给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); 
} 

回答

3

简单地改变参数规范,以反映不会改变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) 
+0

不幸的是,不能解决problem.'initializing”:不能转换从'const Array2D '到'Array2D &' with [ 1> T = INT 转换失去限定符 (22):在编译类模板的成员函数 '行 ::行(常量Array2D &,INT)' – LucidDefender 2011-04-02 02:41:18

+0

@LucidDefender:如果作出的建议的修改,它止跌不要尝试转换为'Array2D &',它会尝试转换为'Array2D const&',这是完全合法的。很明显,你没有正确地提出建议的更改。 – ildjarn 2011-04-02 03:11:00

+0

@Lucid:看起来错误消息来自您在发布之前从“Row :: Row”中删除的代码。更改是必要的,因此您可以尝试修复新的错误,并/或根据需要更新问题。 – Potatoswatter 2011-04-02 03:22:54