TreeInterface.h
#ifndef TreeInterface_h
#define TreeInterface_h
#include"PreconditionException.h"#include"NotFoundException.h"//#include"Tree.hpp"template<class ItemType>
class TreeInterface //: public binarySearchTree<ItemType>
{
virtual void clear()=0;
virtual bool isEmpty()const=0;
virtual int getHeight()=0;
virtual ItemType getRootData() const throw(precondViolated)=0;
virtual bool add(const ItemType& item)=0;
virtual void setItem()=0;
virtual int getNumberOfNodes()const=0;
//virtual ItemType getEntry(const ItemType& anEntry) const throw(NotFoundException)=0;
// int getNumberOfNodes()const;
//virtual void setRootData(const ItemType& item)=0;
//virtual void inorder()=0;
};
#endif /* TreeInterface_h */
Я пытаюсь создать двоичное дерево, но у меня проблема с абстрактным классом. Когда я пытаюсь создать новый экземпляр класса binarySearchTree
это дает мне ошибку: Allocating an object of abstract class type "binarySearchTree"
, Я проверил все свои функции. Я не знаю, что делать. Я думал, что проблема заключается в том, чтобы включить различные файлы, такие как Node.cpp, я не уверен в этом. Я был бы признателен за помощь.
tree.h
#ifndef Tree_h
#define Tree_h
#include"TreeInterface.h"#include"Node.h"//#include"tree.cpp" // should be correct
#include <stdio.h>
#include <iostream>
#include<cstdlib>
#include"PreconditionException.h"#include "NotFoundException.h"using namespace std;
template<class ItemType>
class binarySearchTree: public TreeInterface<ItemType>
{
private:
node<ItemType>* rootPtr;
protected:
int getHeightHelp(node<ItemType>* subTreePtr)const;
void destroyTree(node<ItemType>* subTreePtr);
node<ItemType>* balancedAdd(node<ItemType>* subTreePtr,node<ItemType>* newNodePtr);
node<ItemType>* copyTree(const node<ItemType>* treePtr) const;
public:
binarySearchTree();
binarySearchTree(const ItemType& rootItem);
binarySearchTree(const ItemType& rootItem,binarySearchTree<ItemType>* leftPart,binarySearchTree<ItemType>* rightPart);
binarySearchTree(const binarySearchTree<ItemType>& treePtr);
void clear();
bool isEmpty()const;
int getHeight();
bool add(const ItemType& item);
ItemType getRootData() const throw(precondViolated);
int getNumberOfNodes(node<ItemType>* subtree)const;
void setItem(ItemType item);
};
`
node.h
#ifndef Node_h
#define Node_h
#include <stdio.h>
#include<iostream>
using namespace std;
template<class ItemType>
class node
{
private:
ItemType data;
node<ItemType>* left;
node<ItemType>* right;
public:
node();
node(const ItemType &newdata);
node(const ItemType& item,node<ItemType>* leftPtr,node<ItemType>* rightPtr);
ItemType getNodeItem();
ItemType* getLeftPtr();
ItemType* getRightPtr();
void setLeft(node<ItemType>* newleft);
void setRight(node<ItemType>* newright);
void setNodeItem(ItemType& item);
bool isLeaf() const;
};
Ошибка возникает, когда я пытаюсь создать новый экземпляр binarySearchTree.
main.cpp
#include <iostream>
#include<cstdlib>
#include<string>
#include"Tree.h"using namespace std;
int main()
{
int num=11;
binarySearchTree<int>* node=new binarySearchTree<int>(); //the error is here. Allocating an object of abstract class type "binarySearchTree"node->add(9);
node->isEmpty();
}
Как указывает xaxxon со ссылкой, если у вас есть абстрактный класс (где виртуальная функция = 0), то все функции в базовом классе должны быть переопределены, чтобы создать экземпляр объекта производного класса. Ваша ошибка компилятора говорит вам, что вы не перезаписали все функции.
В вашем случае ваша проблема немного более тонкая. Учтите следующее:
class Abstract
{
public:
virtual bool MyFunction(int x) = 0;
};
class Concrete : public Abstract
{
public:
bool MyFunction() // This does not override Abstract::MyFunction because it is "overloaded", parameters are different
{
return true;
}
};
int main()
{
Concrete concrete;
return 0;
}
Хотя может показаться, что мы переопределяем MyFunction, это не так, потому что параметры разные (у базового класса int x). Так что это не та же самая функция, и Concrete на самом деле все еще абстрактный класс.
Сравните ваши функции: void setItem(ItemType item);
не собирается переезжать virtual void setItem()=0;
в базовом классе
Других решений пока нет …