OOP:设计一个树,在Node类和tree类之间划分功能
OOP: Designing a tree, dividing functionality between Node class and a Tree Class
我需要实现一个自定义树类(使用C++)。在我的整个工作中,我看到了许多树的实现。有些实现了一个向用户公开的"超级节点"类。其(根节点)充当树的实例。有些公开了一个树类,它利用一个节点类来构造一个树。有些将节点类用作纯数据结构,将树构造等功能留给树类。另一些人则把这个节点比作建筑。Split(),到节点类中。
假设您需要设计一个二进制树(如KD树)。从OOP的角度来看,什么是"最好的"方法。节点类是否只包含数据,或者包含将自身拆分为子级的逻辑?一个节点类通常应该包含多少逻辑?
感谢您的建设性意见!
这里有一条OOP规则你应该始终遵循,
每个类都代表一个实体。类具有属性和方法即实体的属性及其行为
因此,你需要遵循你对场景的理解。
以下是我对节点的看法。它有一些数据,一个右节点引用和一个左节点引用。我不认为一个节点应该能够做任何事情,除了向您提供数据,所以我会写一个节点类,比如:
class Node
{
public:
int Data; // yeah, you would obviously use templates, so it's not restricted to a particular type
Node* Left;
Node* Right;
// also you can write constructors and maybe some sort of cast operator overload to be able to make the
// we could also make it return the subtree itself
getRightSubTree(){ return Tree(*Right); }
getLeftSubTree(){ return Tree(*Left); }
};
那么一棵树应该是这样的。
class Tree
{
private:
Node root;
public:
Tree(Node t):root(t){} // every tree should have a root. Cannot be null.
// since the root node will be able to handle the tree structure, now we'll need the necessary methods
void addNode(Node n){
// code here
}
....
getSubTree(int data){
// check if node with that data exists and all
...
Node n = getNode(data);
return Tree(n);
}
};
好吧,我想你现在有个主意了。这一切都是关于你如何看待这个系统。
相关文章:
- C++无法定义虚拟函数 OUTER 类和头文件
- 模板化的类和友元函数
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- 类和静态变量
- 在 c++ 中拆分类和标头中的继承,错误
- 基类和派生类的多态赋值运算符
- 为什么类和 main() 函数中也有动态内存分配
- 将包含抽象类和普通类C++包导出到 Python
- C++ .h 包含从一个类传递到另一个类的类和.cpp
- 重载 + 自己的类和 std::string 的运算符
- 类和类成员的链接
- C++具有模板成员变量的类. 和参数内存输出
- 纯虚拟类和错误未定义对 'vtable 的引用
- 类和构造函数中的函数根本不起作用,并且不返回任何错误
- 标准::在双类和类的 std::p air 上更大
- 你能在类和构造函数中初始化吗,这是否正确?
- Visual Studio 无法解决类和命名空间中重载的明确函数
- 类和朋友在它们之间起作用
- 外部"C"与类和 DLL
- OOP:设计一个树,在Node类和tree类之间划分功能