C++纯虚拟类问题

kre*_*ves 8 c++ polymorphism inheritance

我正在尝试编写一个简单的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
Run Code Online (Sandbox Code Playgroud)

代码是这样的

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;
}
Run Code Online (Sandbox Code Playgroud)

感谢您提供给我的任何信息.

Rob*_*edy 10

编译器似乎很清楚什么是错的.你不能声明a,BBranch因为该类中仍然有一个纯虚函数.您已定义ins,但del仍未定义.在BBranch(和BLeaf)中定义,你应该没问题.

您不能声明抽象类的实例,它们是具有纯虚函数的类.

此外,您已root 在构造函数中声明.你的意思是它是一个成员变量,这意味着它需要在构造函数旁边声明,而不是在里面.

class BTree {
  public:
    BTree() {
    };
    BBranch root;
    void ins( int num );
};
Run Code Online (Sandbox Code Playgroud)