【发布时间】:2020-07-28 09:31:08
【问题描述】:
我正在尝试实现 a-b 树,作为通用树的派生类。 通用树节点如下:
template<typename T>
struct TreeNode
{
T value;
std::vector<TreeNode*> children;
//Some other trivial stuff
};
a-b节点的结构如下:
template<typename T>
struct ABTreeNode : TreeNode<T>
{
std::vector<T> keys;
//The idea is to omit the T value field of the base node and use that vector for the keys
};
在通用树类中也存在一个根字段
TreeNode *root;
而 a-b 构造函数是
template<Typename T>
ABTree<T>::ABTree(T value)
{
GenericTree<T>::root = new ABTreeNode;
root->keys.push_back(value);
}
现在,这种方式,我需要在很多 a-b 树方法中使用向下转换,例如:
template<typename T>
bool ABTree<T>::search(T value)
{
ABTreeNode *node = GenericTree<T>::root;
//....
}//Downcast base to derived
据我所知,向下转换是一种不好的做法,表明设计不好。我使用派生结构中定义的变量但将节点声明为基本结构这一事实似乎很容易出错。如果该节点被创建为基本节点而不是派生的,会发生什么? 例如:
//Somewhere:
TreeNode *node = new TreeNode;//Instead of new ABTreeNode
//..
//Somewhere else
node->keys//Shouldn't that be an error?
我的方法正确吗?如果不是,我应该如何更好地构建它?
PS:请保留原始指针。
【问题讨论】:
-
如果要删除基类的某些数据成员,请不要从该基类继承。
-
那么在这种情况下没有办法使用继承吗?或者在最坏的情况下我应该将键向量放在基本结构中吗?
-
为什么需要继承?如果没有继承,
ABTreeNode应该如何?顺便说一句,如果您知道自己在做什么,那么沮丧并没有那么糟糕。例如,std::list的实现充满了它们。
标签: c++ oop inheritance tree hierarchy