【发布时间】:2015-04-09 22:18:56
【问题描述】:
我有一个这样的树节点类:
class Node
{
public:
Node();
Node(char _value);
~Node();
char getValue() const;
Node* getParent() const;
void addChild(Node* _child);
bool isLeaf() const;
bool isRoot() const;
bool hasChild(char _value) const;
private:
vector<Node*> children;
char value;
Node* parent;
};
我实现了一个 serach 方法:
bool Node::hasChild(char _value) const
{
if (value == _value)
return true;
for (auto it = children.begin(); it != children.end(); it++)
{
if (*it != NULL)
{
(*it)->hasChild(_value);
}
}
}
但是,当我运行此代码时,tmp 变量始终为 false。如果我用调试器跟踪它,return true; 部分会执行,但递归会继续。有什么建议吗?
Node* root = new Node();
Node* a = new Node('a');
Node* c = new Node('c');
root->addChild(a);
root->addChild(c);
bool tmp = root->hasChild('a');
【问题讨论】:
-
我希望任何好的编译器都会在到达非 void 函数的末尾时发出警告,而最后没有任何返回 - 表明问题的一部分。检查你是否这样做。