错误:令牌之前'*'预期的构造函数、析构函数或类型转换|

Error: expected constructor, destructor, or type conversion before '*' token|

本文关键字:构造函数 析构函数 类型转换 令牌 错误      更新时间:2023-10-16

我正在尝试实现一个二进制搜索树。代码并不完整,但我无论如何都会构建它,看看会出现什么可能的错误。这是它的代码:

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

在声明中

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(。

在类声明之外,您需要将作用域前缀为node:

   BST::node* BST::CreateLeaf(int key) { 
// ^^^^^ ...
   }

此外,您不应该包含.cpp文件。包括头,并分别编译和链接.cpp文件。