c++ - 模板化二维数组错误

标签 c++ templates multidimensional-array

尊敬的先生, 当我阅读一本名为“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:\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 ==========

你能花点时间解决我的问题吗?

提前谢谢你。

金李

最佳答案

你需要在这里输入类型名:

template <class T>
typename CArray2D<T>::Row CArray2D<T>::operator [] (unsigned int nRow)
{   
    return Row(*this, nRow);
}

参见 this question .

关于c++ - 模板化二维数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6081292/

相关文章:

c++ - 按值与按引用传递仿函数对象(C++)

c++ - 当我在 'class' 定义之外时,如何编写此模板规范

c++ - 流数据的直方图近似

c++ - 如何在我的dll中集成第三方库?

c++ - 错误到底是什么以及错误地为可 move 和不可复制成员调用复制构造函数有什么解决方法

ruby - 在 Ruby 矩阵中交换列或行

PHP 从多维数组中删除重复值

c++ - qt binarycreator 不创建 dmg

javascript - 将html放入变量时保持美化缩进结构?

java - Java 中 "wrap"ArrayList 的最佳方式?