gpt4 book ai didi

c++ - : expected constructor,析构函数错误,或者 '*' token之前的类型转换|

转载 作者:行者123 更新时间:2023-11-30 03:40:25 25 4
gpt4 key购买 nike

我正在尝试实现二叉搜索树。代码不完整,但我还是构建了它以查看可能出现的错误。这是它的代码:

BST.h
class 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 文件并在头文件中声明了所有函数(并在 main 函数中包含了头文件)。现在正在编译。但是,如果有人能让我知道错误发生的原因,那就太好了。

最佳答案

在声明中

node* BST::CreateLeaf(int key)

…名称node 不为编译器所知,因为它是在BST 类中定义的,并且在该类之外使用。

一个简单的解决方法是使用更新的尾随返回类型语法:

auto BST::CreateLeaf(int key)
-> node*

在这里编译器知道声明属于 BST 类,在它遇到 node 的地方。

或者,您可以限定名称,

BST::node* BST::CreateLeaf(int key)

…但这很快就会变得丑陋,尤其是模板代码。


在其他新闻中,

#include "BST.cpp"

... 在文件 main.cpp 中是不好的做法。一个实际原因是,在 IDE 项目中,这可能会导致代码被编译两次:一次编译 BST.cpp,另一次编译包含在 main.cpp< 中的相同代码.

而是单独编译 BST.cpp

或者,将其设计为头文件模块(主要是将函数声明为inline)。

关于c++ - : expected constructor,析构函数错误,或者 '*' token之前的类型转换|,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38031379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com