模板继承问题

时间:2018-09-20 16:19:34

标签: c++ templates inheritance

我有一个Abstractqueue,我想将其成员继承到另一个子类。当我尝试在主文件中创建子对象时,我不断得到对“ AbstractQueue :: AbstractQueue()”的未定义引用。

enter code here
#ifndef ABSTRACT_QUEUE_H
#define ABSTRACT_QUEUE_H

#include <iostream>

template <class Type>
class AbstractQueue
{
protected:
    Type *items;
    int front;
    int back;
    int capacity;
    int count;
private:
    // data goes here

public:
    AbstractQueue(int s);

   AbstractQueue(void);

   ~AbstractQueue(void);

   bool empty();

   int size();

   Type frontele(); //throw(exception) {}

   Type dequeue(); //throw(exception) {}

   void enqueue ( Type e );
};

template <class Type>
AbstractQueue<Type>::AbstractQueue(int s){
    items = new Type[s];
    front = 0;
    back = 0;
    capacity = s;
    count = 0;
    std::cout << "made the abstract queue!" << std::endl;

}

template <class Type>
AbstractQueue<Type>::~AbstractQueue() {
    delete[] items;
    std::cout << "destructor called" << std::endl;
}

#endif

IncrementalQueue.h

#ifndef _INCREMENTALQUEUE_H
#define _INCREMENTALQUEUE_H

#include "Queue.h"

//#define SIZE = 10

#include <iostream>

template <class Type>
class IncrementalQueue : public AbstractQueue<Type>{

    public:
        //AbstractQueue(void);

       //~AbstractQueue(void);

       IncrementalQueue(int s);

       bool empty();

       int size();

       Type frontele(); //throw(exception) {}

       Type dequeue(); //throw(exception) {}

       void enqueue ( Type e );



    //~IncrementalQueue(void);



    //AbstractQueue(void);

    //AbstractQueue(int size);

    //bool empty(void) ;
        /*if (count == 0) {
        return true;
        }
        else {
        return false;
        }*/

    //int size(void);

    //Type front throw(exception) {}

    //Type dequeue(); //throw(exception) {}

    //void enqueue ( Type e ) ;

        //IncrementalQueue(int size);
};
template <class Type>
IncrementalQueue<Type>::IncrementalQueue(int s){
    this->items = new Type[50];
    this->front = 0;
    this->back = 0;
    this->capacity = 50;
    this->count = 0;
    std::cout << "made the incremental queue!" << std::endl;

}


#endif

main.cpp

#include "Queue.h"
#include "IncrementalQueue.h"

int main(){

    IncrementalQueue<int> incqueue(50);


    return 0;
}

我对模板有些不满意,所以我一直在努力几个小时。有人对我的代码可能失败的地方有任何线索吗?

2 个答案:

答案 0 :(得分:2)

IncrementalQueue::IncrementalQueue()构造函数正在调用AbstractQueue::AbstractQueue()构造函数,而您尚未定义它。

要使其编译,您可以说AbstractQueue() = default;由编译器生成,如果您使用的是C++11或更高版本,请但是不一定正确(请参阅评论)。

答案 1 :(得分:0)

与模板一样,您通常需要将AbstractQueue::AbstractQueue()实现(函数体)放在其标头中,或者,如果您事先知道其所有可能的模板参数,请在此discussion中插入此函数cpp文件:

template class AbstractQueue<NeededType>;

在您的情况下,不可能事先知道所有可能的模板args,因此您需要将函数体放在标头中。那就是单独的单元编译的价格。