#include "Array1D.h"
template <class T>
class CArray2D
{
protected:
unsigned int m_nRows;
unsigned int m_nCols;
CArray1D<T> m_Array1D;
public:
class Row
{
CArray2D& m_Array2D;
unsigned int const m_nRow;
public:
Row(CArray2D& Array2D, unsigned int nRow) : m_Array2D(Array2D), m_nRow(nRow) {}
T& operator [] (unsigned int nCol) const { return m_Array2D.Select(m_nRow, nCol); }
};
CArray2D(unsigned int, unsigned int);
T& Select(unsigned int, unsigned int);
Row operator [] (unsigned int);
};
#include "StdAfx.h"
#include "Array2D.h"
template <class T>
CArray2D<T>::CArray2D(unsigned int nRows, unsigned int nCols)
:m_nRows(nRows),
m_nCols(nCols),
m_Array1D(nRows * nCols)
{
// The constructor takes two arguments, nRows and nCols, which are the desired dimensions of the array.
// It calls the CArray1D<T> class constructor to build a one-dimensional array of size nRows * nCols.
}
template <class T>
T& CArray2D<T>::Select(unsigned int nRows, unsigned int nCols)
{
if (nRows >= m_nRows)
throw std::out_of_range("invalid row");
if (nCols >= m_nCols)
throw std::out_of_range("invalid column");
return m_Array1D[nRows * m_nCols + nCols];
}
template <class T>
CArray2D<T>::Row CArray2D<T>::operator [] (unsigned int nRow)
{
return Row(*this, nRow);
}
当我编译(Microsoft VS 2008 C ++编译器)上面的代码时,我收到了以下错误:
>Compiling...
1>Array2D.cpp
1>f:\tips\tips\array2d.cpp(27) : warning C4346: 'CArray2D<T>::Row' : dependent name is not a type
1> prefix with 'typename' to indicate a type
1>f:\tips\tips\array2d.cpp(27) : error C2143: syntax error : missing ';' before 'CArray2D<T>::[]'
1>f:\tips\tips\array2d.cpp(27) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>f:\tips\tips\array2d.cpp(27) : fatal error C1903: unable to recover from previous error(s); stopping compilation
1>Build log was saved at "file://f:\Tips\Tips\Debug\BuildLog.htm"
1>Tips - 3 error(s), 1 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
你能花点时间弄清楚我的问题吗?
提前谢谢。
金利来答案 0 :(得分:3)
您需要在此输入typename:
template <class T>
typename CArray2D<T>::Row CArray2D<T>::operator [] (unsigned int nRow)
{
return Row(*this, nRow);
}
请参阅this question。
答案 1 :(得分:2)
Row
是一种依赖类型,因此您必须像这样添加typename
:
template <class T>
typename CArray2D<T>::Row CArray2D<T>::operator [] (unsigned int nRow)
有关typename
和相关名称&amp;的详细信息,请参阅this question。类型。