如何使用模板类型作为函数参数来派生抽象模板类(C ++ 11)

时间:2019-12-07 20:47:54

标签: c++11 templates abstract-class virtual-functions template-classes

我被分配编写一个类“ 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";
  }

这是main.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声明为抽象类。我该如何解决,以便我可以重写功能并使BinaryExpressionTree成为非抽象?

1 个答案:

答案 0 :(得分:1)

假设抽象类的定义如下:

template <typename elemType>
class binaryTreeType { ... }

您应按以下方式定义课程:

class binaryExpressionTree : public binaryTreeType<String> { ... }

编辑:原始问题已编辑。

您错误地声明了覆盖函数(在binaryExpressionTree内部)。 您的声明是这样的:

bool search(const string& searchItem) const = 0;

这样的声明会创建一个纯虚方法(由于声明末尾的= 0。纯虚方法(又称为抽象方法)是必须由派生类覆盖的方法。因此,{ {1}}在binaryTreeType中声明其方法为纯虚拟方法,以便实施。

具有尚未实现的抽象方法的类无法实例化-这是编译器生成的错误。

相反,您应该像这样声明您的方法:

binaryExpressionTree

此类声明创建常规的虚函数,该虚函数将覆盖父实现(在这种情况下不存在)。

TL; DR-删除virtual bool search(const elemType& searchItem) const;