错误:令牌之前'*'预期的构造函数、析构函数或类型转换|
Error: expected constructor, destructor, or type conversion before '*' token|
我正在尝试实现一个二进制搜索树。代码并不完整,但我无论如何都会构建它,看看会出现什么可能的错误。这是它的代码:
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文件,并在头文件中声明了所有函数(并在主函数中包含了头文件(。现在它正在编译。但如果有人能让我知道错误最初发生的原因,那就太好了。
在声明中
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
文件。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- new[] / delete[] 并在C++中抛出构造函数/析构函数
- 创建/向容器添加对象时如何使用构造函数/析构函数
- LNK2019构造函数/析构函数使用 C++ Dll
- 有人可以解释一下这里发生了什么(类和构造函数/析构函数)吗?
- 带智能ptr的Pimpl-为什么需要构造函数/析构函数
- 需要构造函数/析构函数/类型转换错误
- Boost共享指针构造函数/析构函数
- 通过值或引用调用时未调用构造函数/析构函数.不管怎样
- C++构造函数析构函数中的奇怪行为
- 构造函数/析构函数链接错误
- 在模板化函数中调用具有特征的显式构造函数/析构函数
- c++构造函数/析构函数
- 为什么赋值的成本不能保证小于构造函数-析构函数对
- 重写默认构造函数/析构函数而不实现它们
- 使用自定义分配器调用对象构造函数/析构函数
- 涉及类和结构的构造函数/析构函数
- 在抽象构造函数/析构函数中调用纯虚拟函数安全吗
- 如果在没有限定的情况下从构造函数/析构函数调用虚拟函数,则是否会发生虚拟调度
- C++基于堆栈的构造函数/析构函数无法按预期工作