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

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条回答 默认 最新

报告相同问题?

悬赏问题

  • ¥15 鸿业暖通修改详细负荷时闪退
  • ¥15 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体