【发布时间】:2016-06-26 02:15:46
【问题描述】:
我正在尝试实现二叉搜索树。代码不完整,但我还是构建了它,看看我会得到什么可能的错误。 这是它的代码:
BST.hclass BST {
public:
struct node
{
//All nodes must be able to point to left and right
int key; //All nodes can hold a key value
node* left; //All nodes have a left pointer
node* right;//All nodes have a right pointer
};
node* root; //References the very top of the tree
public:
BST(); //Constructor that initializes each time instance is called
node* CreateLeaf(int key);
};
BST.cpp
#include<iostream>
#include<cstdlib>
#include "BST.h"
using namespace std;
BST::BST()
{
root = NULL;
}
node* BST::CreateLeaf(int key) //Causing errors
{
node* n = new node;
n->key = key;
n->left = NULL;
n->right = NULL;
return n;
}
main.cpp
#include <iostream>
#include <cstdlib>
#include "BST.cpp"
using namespace std;
int main()
{
return 0;
}
这给出了错误: 错误:“*”标记之前的预期构造函数、析构函数或类型转换
在 BST.cpp 文件中,如果我将 CreateLeaf() 函数声明为:
typedef node* BST::CreateLeaf(int key)
错误变为: 错误:“*”标记之前的预期初始化程序
现在,根据常识,由于我在类之外声明 CreateLeaf 函数,所以我这样做:
BST::node* BST::CreateLeaf(int key)
现在错误变为: 错误:在 BST 函数中:`BST::BST()' 的多个定义
我在 Windows 10 上使用 CodeBlocks IDE。
编辑: 我删除了 .cpp 文件并在头文件中声明了所有函数(并在主函数中包含了头文件)。现在正在编译。但是,如果有人可以让我知道为什么会首先发生错误,那就太好了。
【问题讨论】:
-
错误位置是什么?
-
您不包含 .cpp 文件;这不是它应该如何工作的。
-
youtube.com/… 我使用这个视频作为参考。它适用于他,为什么不适用于我?
-
"为什么不用 "BST.h" 而不是包含 "BST.cpp"。很多人告诉我包含你的源文件是一种不好的做法。"跨度>
标签: c++ binary-tree codeblocks