C ++抽象模板类

时间:2016-03-10 00:09:47

标签: c++ templates

我正在尝试使用抽象模板基类。 编译器在RowArray.cpp中给出了成员rowPntr和rowSize“未在此范围内声明”的错误。两者都是抽象类AbsRow的受保护成员。我猜这种设计是不可能的,因为它利用虚拟函数,它们在运行时动态绑定,但同时使用在编译时绑定的模板。也许混合这两个是问题?我想知道的是,如果我的设计是可行的,为什么我会收到这些编译错误?我也忘了提到在创建RowArray对象RowArray<int> obj(5);时,我在visual studio和Qt creator中得到链接错误2019,它告诉我对RowArray构造函数和析构函数的未定义崇敬。

抽象类AbsRow.h

template <typename T>
class AbsRow
{
public:

     virtual int getSize()const = 0;
     virtual T getValue(int index)const = 0;

protected:

     T *rowPntr;
     int rowSize;
};

派生类RowArray.h

#include "absrow.h"

template <class T>
class RowArray : public AbsRow<T>
{
public:

    RowArray(const int rows);
    virtual ~RowArray();

    virtual T getValue(int index) const override;
    virtual int getSize() const override;

    void setValue(int row, int value);
};

RowArray.cpp

#include "rowarray.h"
#include <cstdlib>

template <class T>
RowArray<T>::RowArray(const int rows)
{
    rowSize = rows;
    rowPntr = new int[rows];

    for(int index = 0; index < rows; index++)
    {
        rowPntr[index] = (rand() % 90) + 10;
    }
}

template <class T>
RowArray<T>::~RowArray()
{
    delete [] rowPntr;
}

template <class T>
void RowArray<T>::setValue(int row, int value)
{
    rowPntr[row] = value;
}

template <class T>
int RowArray<T>::getSize() const
{
    return rowSize;
}

template <class T>
T RowArray<T>::getValue(int index) const
{
    return rowPntr[index];
}

主要

#include "rowarray.h"

int main()
{
    RowArray<int> row(7);
}

3 个答案:

答案 0 :(得分:1)

你可以基本上以两种方式解决这个问题......以RowArray.cpp的缩短示例... (我还修复了new表达式中的问题)

template <class T>
RowArray<T>::RowArray(const int rows)
{
    AbsRow<T>::rowSize = rows
    // or
    //this->rowSize = rows;

    AbsRow<T>::rowPntr = new T[rows];   ///Corrected 'int' to 'T' because rowPntr is of type 'T*' in your AbsRow class
    // or
    //this->rowPntr = new T[rows];

    for(int index = 0; index < rows; index++)
    {
        AbsRow<T>::rowPntr[index] = (rand() % 90) + 10;
        // or
        //this->rowPntr[index] = (rand() % 90) + 10;
    }
}

答案 1 :(得分:0)

我认为错误来自于您将模板代码(派生类仍然是模板)放入CPP文件中。编译器必须看到整个模板实现,这通常意味着将整个事物放在头文件中。

另一个问题是派生类构造函数假定类型为rowPntr的{​​{1}},但它确实是int*

答案 2 :(得分:0)

这里问题的根本原因是,它应该在.h文件本身中具有模板类的函数定义。如果您没有这样做,编译器将无法链接.cpp文件中的定义。很少有黑客可以克服这个问题。一种是在.cpp文件中进行显式模板初始化。

在RowArray.cpp上添加

template class AbsRow<int>;
template class RowArray<int>;

相关问题