我正在尝试编写一个简单的 B+ 树实现(非常早期的阶段)。我有一个具有一些功能的虚拟类。不用说,我对这些策略还很陌生,并且遇到了各种各样的问题。
我正在尝试在 BTree 类中创建一个根节点。根节点将是一个 BBranch,它应该继承自 BNode?我收到错误
btree.cpp: In constructor âBTree::BTree()â:
btree.cpp:25: error: cannot declare variable ârootâ to be of abstract type âBBranchâ
btree.cpp:12: note: because the following virtual functions are pure within âBBranchâ:
btree.cpp:9: note: virtual void BNode::del(int)
btree.cpp: In member function âvoid BTree::ins(int)â:
btree.cpp:44: error: ârootâ was not declared in this scope
代码是这样的
using namespace std;
class BNode {
public:
int key [10];
int pointer [11];
virtual void ins( int num ) =0;
virtual void del( int num ) =0;
};
class BBranch: public BNode {
public:
void ins( int num );
};
class BLeaf: public BNode {
public:
void ins( int num );
};
class BTree {
public:
BTree() {
BBranch root;
};
void ins( int num );
};
// Insert into branch node
void BBranch::ins( int num ){
// stuff for inserting specifically into branches
};
// Insert for node
void BTree::ins( int num ){
root.ins( num );
};
int main(void){
return 0;
}
感谢您提供的任何信息。
最佳答案
编译器似乎很清楚哪里出了问题。您不能声明 BBranch
,因为该类中仍然有一个纯虚函数。您定义了 ins
,但 del
仍未定义。在 BBranch
(和 BLeaf
)中定义它,您应该没问题。
您不能声明抽象类的实例,抽象类是具有纯虚函数的类。
此外,您已经在构造函数中声明了 root
。你的意思是它是一个成员变量,这意味着它需要在构造函数旁边而不是内部声明。
class BTree {
public:
BTree() {
};
BBranch root;
void ins( int num );
};
关于C++纯虚类问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1172792/