【问题标题】:Declaring a struct method in C++在 C++ 中声明一个结构方法
【发布时间】:2010-10-17 00:13:12
【问题描述】:

我正在尝试在我的代码中创建一个循环结构方法来遍历二叉搜索树。但是我在编译时遇到错误并且不确定是什么原因。

我在 .h 文件的私有部分中有 Node* findNode(const Node *, const Object &);

Node* BSTree::findNode(const Node* current, const Object &target){
if(*current->item == target)
    return current;

Node* temp = NULL;

if(current->nodeLeft != NULL){
    temp = findNode(current->nodeLeft, target);

    if(temp != NULL)
        return temp;
}

if(current->nodeRight != NULL){
    temp = findNode(current->nodeRight, target);

    if(temp != NULL)
        return temp;
}
return NULL;

}

在 cpp.

我正在生成以下错误:

-error C2143:语法错误:缺少';'在'*'之前
-error C4430:缺少类型说明符 - 假定为 int。注意:C++ 不支持 default-int
-error C4430:缺少类型说明符 - 假定为 int。注意:C++ 不支持 default-int
-error C2556: 'int *BSTree::findNode(const BSTree::Node *,const Object &)' : 重载函数的不同之处仅在于返回类型来自 'BSTree::Node *BSTree::findNode(const BSTree::Node * ,const 对象 &)'

编译器错误都指向cpp中代码的第一行。我尝试查找错误代码,但没有找到任何可以回答我关于原因的问题的内容。

是什么导致了错误,为什么我的编译器在“int BSTree”而不是 Node* BSTree 上读取它?我是在犯语法错误还是忘记包含?目前我只包含了 iostream 和 fstream。

我提前感谢任何花时间阅读本文的人。

编辑:

回答科林的问题。

我的 .cpp 中有 #include "BSTree.h"

在 .h 中我有:

 #ifndef BSTREE_H  
 #define BSTREE_H  

 #include <iostream>  
 #include <fstream>  

【问题讨论】:

  • 您包含了 iostream 和 fstream,但您是否包含了 .h 文件?
  • 另外,听起来编译器找不到 Node 的定义 - 请确保在您的 .h 文件中也包含该 .h 文件
  • 请使用“1010101”按钮格式化,而不是在第一行和最后一行添加缩进。
  • 土豆拍你指的是什么位?我使用“1010101:代码位按钮。除了我在编辑中添加的最后一点。

标签: c++ struct


【解决方案1】:

从错误来看,您似乎在 BSTree 结构中声明了 Node。我认为您的问题在于您的返回类型。尝试将返回类型声明为BSTree::Node*

【讨论】:

  • ……也就是说,BSTree::Node* BSTree::findNode(const Node* current
  • 啊,解决了。谢谢你。并感谢您的澄清 Potatoswatter
【解决方案2】:

您已经得到了您所提问题的答案。我将添加一些关于如何编写代码的内容。我更喜欢这样的东西:

Node* BSTree::findNode(const Node* current, const Object &target){
    if (current == NULL)
        return NULL;

    if (target < current->item)
        return findNode(current->left, target);
    if (current->item < target)
        return findNode(current->right, target);
    return current;
}

这(可能)继续递归直到current == NULL,而不是尝试在current-&gt;left == NULLcurrent-&gt;right == NULL 时停止,具体取决于选择的方向。虽然这可以节省一层递归,但它需要将几乎所有的递归逻辑复制到左右分支中才能做到这一点。除非您确实确定递归非常昂贵,否则检查当前节点是否为 NULL 可以通过合并两者来简化代码。这个版本的代码还有一个优点是(像大多数 C++ 容器一样)它只需要Object 来定义operator&lt;,而不是operator==

如果你想更进一步,你可以将左右分支的指针放在一个数组中,进一步简化代码:

// presumes BSTree::Node is defined something like this:
class BSTree {
    class Node { 
        // subnodes[0] == left subtree
        // subnodes[1] == right subtree
        Node subnodes[2];
    };
};

BSTree::Node* BSTree::findNode(const Node* current, const Object &target){
    if (current == NULL)
        return NULL;

    if (current->item == target) 
        return current;

    return findNode(subnodes[target < current->item]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多