我刚刚在我的程序中发现了一些非常奇怪的行为。我有一棵树,其中每个节点都是 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/