从递归定义的类继承
Inherit from recursively defined class
我有一个这样定义的四叉树:
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>{};
则类型转换可以避免
相关文章:
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- 如何定义一个没有重复代码的继承的 const 类成员函数?
- 如何创建没有特定定义的随机分布?uniform_int_distribution是从其他类继承的吗?
- C++ 定义继承方案
- 从第三方定义的类继承时shared_from_this
- 自定义异常中的用户定义的空构造函数,具有多个继承和抽象基类
- 类继承自QLabel,为什么不调用自定义插槽?
- 继承依赖类型定义而不使用结构
- 如何正确消除继承类型定义的歧义?以及如何简化他们的创作?
- C++中的继承和构造函数定义
- 从模板继承的 MSVC DLL 导出类会导致LNK2005已定义的错误
- 模板化类继承的子类定义中的错误
- 定义多次继承的虚拟方法
- 继承中的函数定义
- C++对已继承的受保护类成员的未定义引用
- C 中的继承:在亲子类中定义变量
- 是否可以定义一个在外部"C"块中继承另一个结构的结构?
- C++继承:定义指向派生类或基类的指针
- 为什么我们不能为继承定义一个匿名类?