从递归定义的类继承

Inherit from recursively defined class

本文关键字:继承 定义 递归      更新时间:2023-10-16

我有一个这样定义的四叉树:

class QuadTree{
public:
    QuadTree(): is_leaf(false), NW(NULL), NE(NULL), SW(NULL), SE(NULL) {};
    // Pointers to children (northwest etc.)
    QuadTree* NW;
    QuadTree* SW;
    QuadTree* SE;
    QuadTree* NE;
    bool is_leaf;
    int value;
};

我想继承该类,例如

class SpecialQuadTree: public QuadTree{
public:
    int foo;
};

然而,这并不像预期的那样工作:

void insertValueIntoTree(int value, SpecialQuadTree* tree){
    if(is_leaf){
        tree->value = value;
        return;
    }
    if(/*north-west is the right tree to insert into*/){
        tree->foo = 42;
        insertValueIntoTree(value, tree->NW); // error
    }else if(...){
        /*possibly insert into other children*/;
    }
}

编译器抱怨无法从QuadTree*转换为SpecialQuadTree*。当然,指向子对象的指针仍然是指向基类对象的指针。

我如何从基类继承,并且的指针是指向派生类的指针?

编辑:我编辑了代码以更好地反映我的意图:我必须使用派生类,因此不能更改签名。

当然,指向孩子们的指针仍然是指向基地的指针类对象。

,但是基的指针不是子类对象的指针。不能从QuadTree*隐式转换为SpecialQuadTree*。如果从QuadTree派生出另外一个OneMoreSpecialQuadTree类,并且您将此对象存储在指针NW中,该怎么办。您需要更改insertValueIntoTree的签名才能接受QuadTree*

您应该使用模板来实现这个

template<class Subtype>
class QuadTree{
public:
    QuadTree(): is_leaf(false), NW(NULL), NE(NULL), SW(NULL), SE(NULL) {};
    // Pointers to children (northwest etc.)
    Subtype* NW;
    Subtype* SW;
    Subtype* SE;
    Subtype* NE;
    bool is_leaf;
    int value;
};

并将您的SpecialQuadTree定义为:

class SpecialQuadTree: public QuadTree<SpecialQuadTree>{};

则类型转换可以避免