一个简单的二叉搜索树类声明:
#include <vector>
#include <stdio.h>
// Provides various structures utilized by search algorithms.
// Represents an generalized node with integer value and a set of children.
class Node {
protected:
std::vector<Node*> children;
int value;
public:
//Creates a new instance of a Node with a default value=-1.
Node(){value = -1;}
//Creates a new instance of a Node with a specified value.
explicit Node(int value){this->value = value;}
virtual ~Node(){delete children;}
//Adds new Node with specified value to the list of child nodes. Multiple
//children with the same value are allowed.
//Returns added node.
virtual Node* Insert(int value);
//Removes first occurrence of a Node with specified value among children.
virtual void Remove(int value);
};
// Represents a binary search tree node with at most two children.
class BTNode: public Node {
public:
//Creates a new instance of a BTNode with a default value=-1.
BTNode():Node(){}
//Creates a new instance of a BTNode with a specified value.
explicit BTNode(int value):Node(value){}
//Adds new BTNode with specified value to the list of child nodes in an
//ordered manner, that is right child value is >= value of this node and
//left child value < value of this node.
virtual BTNode* Insert(int value);
//Removes first occurrence of a Node with specified value from the tree.
virtual void Remove(int value);
//Returns a node with specified value.
virtual BTNode* Search(int value);
};
eclipse抱怨它的定义:
BTNode* BTNode::Search(int value){
if (this->value == value) return *this;
//Determines whether value is in left(0) or right(1) child.
int child = this->value > value ? 0 : 1;
if (children[child] != NULL)
return children[child]->Search(value);
return NULL;
}
调用children[child]->Search(value)
的确切位置,并显示消息“方法搜索无法解析”。 Build运行得很好(没有任何编译错误)。有什么问题?
P.S.:尚未尝试运行代码,但是。正在努力。
答案 0 :(得分:2)
Search
是BTNode
界面的一部分,但它不是Node
界面的一部分,children
是vector
的{{1}}因此,在Node*
上拨打Search
无效。如果Node *
有Node
方法是有意义的,那么将其添加到Search
会解决该问题。如果没有,那么你需要重新考虑你的设计,这可能超出了这个问题的范围。
还有一些其他问题。你有:
Node
但virtual ~Node(){delete children;}
不是children
,而是pointer
。您需要遍历std::vector<Node*>
并调用vector
每个元素。在delete
中你有这个:
Search
但if (this->value == value) return *this;
会返回Search
,因此应该是:
BTNode*