c++ - C++ 中的多态递归调用?

标签 c++ algorithm recursion polymorphism

我刚刚在我的程序中发现了一些非常奇怪的行为。我有一棵树,其中每个节点都是 Node 的子类。我通过遍历树递归计算边界框,直到到达叶节点处的单元基元(即 Cube : Node)。

递归函数 getBoundingBox() 声明为虚函数并正确遍历树。叶节点覆盖该函数并返回一个单位立方体。

但是,当我跟踪程序时,覆盖似乎对递归函数 getBoundingBox() 没有影响,即使它对另一个函数(如 getName())工作得很好。

示例:

class Node;

typedef shared_ptr<Node> node_ptr;

class Node
{
protected:
  vector<node_ptr> mChildren;
public:
  virtual string getName() { return "Node";}
  virtual BoundingBox getBoundingBox()
  {
    //Merge Bounding Boxes of Children
    BoundingBox bb = BoundingBox();
    //For each child
    for(vector<node_ptr>::iterator it = mChildren.begin(); it != mChildren.end(); ++it) {
      string name = (*it)->getName();//Correctly returns Node or Cube depending on type of (*it)
      bb = BoundingBox::Merge(bb, (*it)->getBoundingBox());//Always calls Node::getBoundingBox(); regardless of type
    }
    return bb;
  }
};

class Cube : public Node
{
public:
  virtual string getName() { return "Cube";}
  virtual BoundingBox getBoundingBox()
  {
    return BoundingBox::CreateUnitCube();
  }
};

关于 c++ 中的递归多态性,我是否缺少某种警告?

最佳答案

我认为您的继承结构一团糟。拥有一个可能是抽象的基类 Node 更有意义

class BaseNode {
public:
  virtual BoundingBox getBoundingBox() const = 0;
};

然后定义不同类型的节点

using node_ptr = std::shared_ptr<BaseNode>;
class Node : public BaseNode
{
  std::vector<node_ptr> mChildren;
public:
  BoundingBox getBoundingBox() const noexcept
  {
    BoundingBox bb;
    for(auto pc:mChildren)
      bb.merge(pc->getBoundingBox());
    return bb;
  }
};

class Cube : public BaseNode
{
public:
  BoundingBox getBoundingBox() const noexcept
  { return BoundingBox::CreateUnitCube(); }
};

关于c++ - C++ 中的多态递归调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19408407/

相关文章:

c - 使用递归函数反向打印链表

python - 如何递归调用python中的函数将列表中的每个元素拖到底部?

c++ - 以编程方式获取共享库中的函数名称

c++ - 未在范围内声明,即使在 .h 中声明

c++ - boost managed_mapped_file : setting maximum allowed memory usage

database - 处理以下用例要求的数据结构

algorithm - 计算 FOR 循环标记如何影响复杂性

c++ - gsl_vector 有 count_if 函数吗? C/C++

algorithm - Dijkstra算法中未访问的节点?

c++ - 了解递归函数的执行顺序