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);
}
不幸的是,不能解決problem.'initializing」:不能轉換從'const Array2D'到'Array2D &' with [ 1> T = INT 轉換失去限定符 (22):在編譯類模板的成員函數 '行 ::行(常量Array2D &,INT)' –
LucidDefender
2011-04-02 02:41:18
@LucidDefender:如果作出的建議的修改,它止跌不要嘗試轉換爲'Array2D&',它會嘗試轉換爲'Array2D const&',這是完全合法的。很明顯,你沒有正確地提出建議的更改。 –
ildjarn
2011-04-02 03:11:00
@Lucid:看起來錯誤消息來自您在發佈之前從「Row :: Row」中刪除的代碼。更改是必要的,因此您可以嘗試修復新的錯誤,並/或根據需要更新問題。 – Potatoswatter 2011-04-02 03:22:54