簡體   English   中英

C ++中的多態遞歸調用?

[英]Polymorphic recursive calls in C++?

我剛剛在程序中發現了一些非常奇怪的行為。 我有一棵樹,其中每個節點的子類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(); }
};

Cube數據集不是Node因為您沒有使用公共繼承。

我不確定您的實際代碼如何編譯,但是嘗試將其更改為:

class Cube : public Node

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM