亲爱的先生,当我阅读一本名为"C++中具有面向对象设计模式的数据结构和算法"的在线书籍时,我从"二维数组实现"部分中剪切并粘贴了一些代码片段(请参阅此链接以供参考 http://www.brpreiss.com/books/opus4/html/page102.html),如下所示:
#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:tipstipsarray2d.cpp(27) : warning C4346: 'CArray2D<T>::Row' : dependent name is not a type
1> prefix with 'typename' to indicate a type
1>f:tipstipsarray2d.cpp(27) : error C2143: syntax error : missing ';' before 'CArray2D<T>::[]'
1>f:tipstipsarray2d.cpp(27) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>f:tipstipsarray2d.cpp(27) : fatal error C1903: unable to recover from previous error(s); stopping compilation
1>Build log was saved at "file://f:TipsTipsDebugBuildLog.htm"
1>Tips - 3 error(s), 1 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
你能花点时间弄清楚我的问题吗?
提前谢谢你。
金李
您需要在此处输入类型名称:
template <class T>
typename CArray2D<T>::Row CArray2D<T>::operator [] (unsigned int nRow)
{
return Row(*this, nRow);
}
看到这个问题。
Row
是一个依赖类型,因此您必须添加如下typename
:
template <class T>
typename CArray2D<T>::Row CArray2D<T>::operator [] (unsigned int nRow)
有关typename
和从属名称和类型的详细信息,请参阅此问题。