0

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

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*。当然,指向孩子的指针仍然是指向基类对象的指针。

如何从基类继承使其指针成为派生类的指针?

编辑:我已经编辑了代码以更好地反映我的意图:我必须使用派生类的成员,因此更改签名不是一种选择。

4

2 回答 2

2

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

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

于 2013-07-04T12:41:21.733 回答
1

您应该使用模板来实现这一点

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>{};

那么可以避免类型转换

于 2013-07-04T12:54:09.043 回答