小白一只,学习类模板的时候遇到一点问题
下面的代码中seqQueue是派生类
queue是基类,queue的成员函数都是纯虚函数
在主函数中用基类的指针指向派生类,为什么会报错?
#include<iostream>
using namespace std;
#include"CHAPTER4_2.h"
int main(){
seqQueue<int> a(5);
queue<int>* b = &a;
int x;
for (int i = 0; i < 5; i++) {
cin >> x;
b->enQueue(x);
}
cout << b->getHead() << endl;
b->deQueue();
cout << b->getHead() << endl;
return 0;
}
基类定义:
#ifndef CHAPTER4_1
#define CHAPTER4_1
#include<iostream>
using namespace std;
template<class elemType>
class queue
{
public:
virtual bool isEmpty()const = 0;
virtual void enQueue(const elemType& x) = 0;
virtual elemType deQueue() = 0;
virtual elemType getHead()const = 0;
virtual ~queue(){}
};
#endif // !CHAPTER4_1
派生类定义:
#ifndef CHAPTER4_2
#define CHAPTER4_2
#include<iostream>
using namespace std;
#include"CHAPTER4_1.h"
template<class elemType>
class seqQueue:public queue{
private:
elemType* elem;
int maxSize;
int rear, front;
void doubleSpace() {
elemType* tmp = elem;
elem = new elemType[maxSize * 2];
for (int i = 1; i < maxSize; i++) {
elem[i] = tmp[(front + i) % maxSize];
}
}
public:
seqQueue(int size = 10)
{
elem = new elemType[size];
rear = front = 0;
maxSize = size;
}
~seqQueue()
{
delete[]elem;
}
bool isEmpty()const
{
return rear == front;
}
void enQueue(const elemType& x)
{
if ((rear + 1) % maxSize == front)doubleSpace();
rear = (rear + 1) % maxSize;
elem[rear] = x;
}
elemType deQueue() {
front = (front + 1) % maxSize;
return elem[front];
}
elemType getHead()const
{
return elem[(front + 1) % maxSize];
}
};
#endif // !CHAPTER4_2
报错截图: