【问题标题】:Eclipse complains about recursive function callEclipse 抱怨递归函数调用
【发布时间】:2013-04-12 13:21:22
【问题描述】:

一个简单的二叉搜索树类声明:

#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]-&gt;Search(value) 的确切位置出现消息“方法搜索无法解析”。 构建运行良好(没有任何编译错误)。这有什么问题?

P.S.:还没有尝试运行代码。正在努力。

【问题讨论】:

  • 你说 Eclipse 抱怨。是在编译期间还是仅在它尝试解析您的代码以分析它以进行自动完成等时?
  • @JohnZwinck,添加了更多细节。所以这是第二种选择。

标签: c++ class implementation


【解决方案1】:

SearchBTNode 接口的一部分,但它不是Nodes 接口的一部分,childrenNode*vector,因此在a 上调用Search 是无效的Node *。如果Node 有一个Search 方法是有意义的,那么将它添加到Node 将解决这个问题。如果不是,那么您需要重新考虑您的设计,这可能超出了这个问题的范围。

还有其他一些问题。你有:

virtual ~Node(){delete children;}

children 不是pointer,而是std::vector&lt;Node*&gt;。您需要遍历 vector 并调用 delete 每个元素。在Search 你有这个:

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

但是 Search 返回一个 BTNode* 所以它应该是:

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

【讨论】:

  • 有道理。您能否为我的目的提出设计改进或最佳实践? (我对 C++ 比较陌生)
  • 我是否正确理解了我需要遍历指针向量并为每个指针调用 delete?
  • @DenysS。刚刚更新的答案,您需要遍历 vector 并在每个元素上调用 delete
猜你喜欢
  • 2016-01-08
  • 2011-11-12
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-28
相关资源
最近更新 更多