我被指派编写一个类"binaryExpressionTree",该类派生自抽象模板类"binaryTreeType"。 binaryExpressionTree的类型为String。作为作业的一部分,我必须从binaryTreeType覆盖这3个虚拟函数:
//Header File Binary Search Tree
#ifndef H_binaryTree
#define H_binaryTree
#include <iostream>
using namespace std;
//Definition of the Node
template <class elemType>
struct nodeType
{
elemType info;
nodeType<elemType> *lLink;
nodeType<elemType> *rLink;
};
//Definition of the class
template <class elemType>
class binaryTreeType
{
public:
virtual bool search(const elemType& searchItem) const = 0;
virtual void insert(const elemType& insertItem) = 0;
virtual void deleteNode(const elemType& deleteItem) = 0;
binaryTreeType();
//Default constructor
};
binaryTreeType<elemType>::binaryTreeType()
{
}
#endif
以下是到目前为止我对binaryExpressionTree的了解:
#define EXPRESSIONTREE_H
#include "binaryTree.h"
#include <iostream>
#include <string>
class binaryExpressionTree : public binaryTreeType<string> {
public:
void buildExpressionTree(string buildExpression);
double evaluateExpressionTree();
bool search(const string& searchItem) const = 0;
void insert(const string& insertItem) = 0;
void deleteNode(const string& deleteItem) = 0;
};
这是binaryExpressionTree.cpp:
#include <string>
#include <cstring>
#include <stack>
#include <cstdlib>
#include <cctype>
#include "binaryExpressionTree.h"
#include "binaryTree.h"
using namespace std;
bool binaryExpressionTree::search(const string& searchItem) const {
return false;
}
void binaryExpressionTree::insert(const string& insertItem) {
cout << "this";
}
void binaryExpressionTree::deleteNode(const string& deleteItem) {
cout << "this";
}
这是主要.cpp:
#include <iostream>
#include <iomanip>
#include <fstream>
#include "binaryExpressionTree.h"
int main()
{
binaryExpressionTree mainTree = binaryExpressionTree(); //Error:[cquery] allocating an object of abstract class type 'binaryExpressionTree'
return 0;
}
问题是,由于binaryExpressionTree是String类型的派生类,它不知道"elemType"是什么意思,我需要更改searchItem, insertItem and deleteItem
到字符串和对象。但是一旦我这样做了,编译器就不再认识到我正在覆盖虚函数(因为我已经更改了它们的参数(,并将 binaryExpressionTree 声明为抽象类。我该如何解决这个问题,以便我可以覆盖函数并使二进制表达式树非抽象?
假设抽象类是这样定义的:
template <typename elemType>
class binaryTreeType { ... }
应按如下方式定义类:
class binaryExpressionTree : public binaryTreeType<String> { ... }
编辑:原始问题已编辑。
您错误地声明了覆盖函数(在二进制表达式树中(。 您的声明是这样的:
bool search(const string& searchItem) const = 0;
此类声明创建一个纯虚拟方法(因为声明末尾= 0
。纯虚拟方法(又名抽象方法(是必须由派生类重写的方法。因此,binaryTreeType
声明其方法纯虚拟,以便您实现,在binaryExpressionTree
.
具有尚未实现的抽象方法的类无法实例化 - 这是编译器生成的错误。
相反,您应该像这样声明您的方法:
virtual bool search(const elemType& searchItem) const;
这样的声明会创建常规的虚拟函数,它将覆盖父实现(在这种情况下不存在(。
TL;DR - 删除= 0
。