2013-04-12 91 views
0

一個簡單的二叉搜索樹類聲明:Eclipse的抱怨遞歸函數調用

#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)發生了消息「方法搜索無法解析「。 構建運行良好(沒有編譯錯誤)。那有什麼問題?

P.S.:Haven't嘗試運行代碼,但。在它上面工作。

+0

你說Eclipse的抱怨。在編譯過程中,還是在它試圖解析代碼以分析它以進行自動完成等? –

+0

@JohnZwinck,增加更多細節。所以這是第二種選擇。 –

回答

2

SearchBTNode接口的一部分,但它不是Node s接口的一部分,childrenNode*一個vector,因此是無效的調用SearchNode *。如果Node有一個Search方法,然後將其添加到Node將解決該問題。如果沒有,那麼你需要重新考慮你的設計,這可能超出了這個問題的範圍。

還有一些其他問題。您有:

virtual ~Node(){delete children;} 

children不是pointer它是一個std::vector<Node*>。您需要迭代vector並調用delete每個元素。在Search你有這樣的:

if (this->value == value) return *this; 

Search返回BTNode*所以應該是:

if (this->value == value) return this ; 
+0

有道理。你能爲我的目的建議設計改進或最佳實踐嗎? (我相當新的C++) –

+0

我是否正確地得到它,我需要遍歷指針的向量和每個指針調用刪除? –

+0

@DenysS。剛剛更新的答案,你需要遍歷每個元素上的'vector'並調用'delete' –