继承自递归定义的类

时间:2013-07-04 12:38:44

标签: c++ inheritance recursion

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

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

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

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

2 个答案:

答案 0 :(得分:2)

  

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

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

答案 1 :(得分: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>{};

然后可以避免类型转换

相关问题