m0_54906215
2021-01-28 15:30
采纳率: 100%
浏览 52

vs2019中,派生类的定义和实现放在两个文件中为什么会报错?

使用vs2019,学习类模板的时候遇到一些不能理解的报错,希望有大佬可以帮助解答

首先我定义了一个基类,内部的函数都是纯虚函数,放在文件CHAPTER4_1.h,代码如下:

#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

之后定义派生类,放在CHAPTER4_6.h中,代码如下:

#ifndef CHAPTER4_6
#define CHAPTER4_6

#include<iostream>
using namespace std;
#include"CHAPTER4_1.h"

template<class elemType>
class linkQueue :public queue<elemType>
{
private:
	struct node {
		elemType data;
		node* next;
		node(const elemType& x, node* N = NULL) {
			data = x;
			next = N;
		}
		node():next(NULL){}
		~node(){}
	};
	node* front, * rear;
	
public:
	linkQueue();
	~linkQueue();
	bool isEmpty()const;
	void enQueue(const elemType& x);
	elemType deQueue();
	elemType getHead()const;
};

#endif // !CHAPTER4_6

然后在CHAPTER4_6.cpp文件中,实现派生类中的函数,代码如下:

#include<iostream>
using namespace std;
#include"CHAPTER4_6.h"

template<class elemType>
linkQueue<elemType>::linkQueue() {
	front = rear = NULL;
}

template<class elemType>
linkQueue<elemType>::~linkQueue() {
	node* tmp;
	while (front != NULL) {
		tmp = front->next;
		delete front;
		front = tmp;
	}
}

template<class elemType>
bool linkQueue<elemType>::isEmpty()const {
	if (front == NULL)return true;
}

template<class elemType>
void linkQueue<elemType>::enQueue(const elemType& x) {
	if (rear == NULL) {
		rear = front = new node(x);
	}
	else {
		rear->next = new node;
		rear = rear->next;
		rear->data = x;
	}
}

template<class elemType>
elemType linkQueue<elemType>::getHead()const {
	return front->data;
}

template<class elemType>
elemType linkQueue<elemType>::deQueue() {
	elemType value;
	if (rear == front && rear != NULL) {
		delete rear;
		rear = front = NULL;
	}
	else {
		node* tmp;
		value = tmp->data;
		tmp = front;
		front = front->next;
		delete tmp;
	}
	return value;
}

最后是main函数,放在main.cpp中:

#include<iostream>
#include"CHAPTER4_6.h"
using namespace std;

int main() {
	queue<int>* a;
	linkQueue<int> b;
	a = &b;
	for (int i = 0; i < 5; i++) {
		a->enQueue(i);
	}
	cout << a->getHead() << endl;
	a->deQueue();
	cout << a->getHead() << endl;
	return 0;
}

但是运行之后会报错,如果把派生类的实现放在CHAPTER4_6.h文件中就可以正常运行

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题