儿童类的自定义容器c ++

时间:2017-12-17 01:32:58

标签: c++11 templates inheritance containers

我正在尝试制作一个更改和比较不同文档字段的程序。有一个基类具有虚函数和一些子类。为方便起见,我想将子类的对象放入表示线性堆栈的自定义容器中。这是标题代码:

template <class T>

class DocContainer{
public:
    struct ListElement{ // the stack itself
        T obj;
        ListElement *next;
    };
    DocContainer();
    ~DocContainer();

    void pop_top();
    T &get_top() const;
    T &operator[](int);
    void push_top(const T &);
    int size() const;
    void clear();

private:
        ListElement *first;
        int num;
};

我试图谷歌如何为不同类型的对象实现容器,并发现我应该使用多态来包含指向父类的指针。但当我尝试使用它时:

Passport *pass = new Passport;
// some code
DocContainer<Document*> DC;
DC.push_top(dynamic_cast<Document*>(pass));

编译器说:

  

未定义引用`DocContainer :: push_top(文档*   常量&安培)'

关于容器的构造函数和析构函数的相同警告。

Class Passport是Document的子类。

class Passport : public Document{
// some code
};

.cpp文件中容器的push_top()函数:

template <class T>
void DocContainer<T>::push_top(const T &A){ 
    auto cur = new ListElement;
    cur->obj = A;
    cur->next = first;
    first = cur;
    num++;
    delete cur;
}

肯定有一些错误,但我找不到任何明确的答案。怎么了? 提前致谢

0 个答案:

没有答案