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

时间:2013-10-16 16:10:19

标签: c++ algorithm recursion polymorphism

我刚刚在程序中发现了一些非常奇怪的行为。我有一棵树,其中每个Node都是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 ++中的递归多态,是否存在某种警告?

2 个答案:

答案 0 :(得分:1)

我认为你的继承结构混乱了。拥有一个可能是抽象的基类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(); }
};

答案 1 :(得分:0)

Cube不是Node,因为您没有使用公共继承。

我不确定您的实际代码是如何编译的,但请尝试将其更改为:

class Cube : public Node