类继承,ENUM 与 AST 类实现的问题

Class Inheritance, ENUM issues with AST class implementations

本文关键字:实现 问题 AST 继承 ENUM      更新时间:2023-10-16

我目前正在用玩具语言Micro进行编译器项目,该项目使用Bison和C++实现。 我创建了一些类来处理构建 AST 以评估表达式,并尝试通过继承来实现这一点。 我有一个父类 ASTNode,我想定义像 AddExprNode 这样的子类,如下所示。

我在子类中使用 ASTNode.hpp 中的枚举 (ASTNodeType( 时特别遇到问题,并且收到有关类名的问题。 我一直试图自己研究这些,但遇到了很多麻烦。

为什么 g++ 找不到类名,为什么它不知道 ASTNodeType 已被声明? 以下是我收到的错误,然后是我的代码。

错误:

In file included from src/AddExprNode.cpp:3:
src/AddExprNode.hpp:13: error: expected class-name before ‘{’ token
src/AddExprNode.hpp:18: error: ‘ASTNodeType’ has not been declared
src/AddExprNode.cpp:8: error: ‘ASTNodeType’ has not been declared
src/AddExprNode.cpp: In constructor ‘AddExprNode::AddExprNode(std::string,     int)’:
src/AddExprNode.cpp:8: error: ‘ASTNode’ has not been declared
src/AddExprNode.cpp:8: error: expected ‘{’ before ‘ASTNode’
src/AddExprNode.cpp: At global scope:
src/AddExprNode.cpp:8: error: expected constructor, destructor, or type conversion before ‘(’ token

ASTNode.hpp:

#include <string>
enum class ASTNodeType
{
UNDEFINED,
ADD_EXPR,
MULT_EXPR,
VAR_REF
};
class ASTNode
{
public:
ASTNodeType Type;
ASTNode * Left;
ASTNode * Right;
ASTNode();
ASTNode(ASTNodeType type);
void setType(ASTNodeType Type);
void setLeftChild(ASTNode * Left);
void setRightChild(ASTNode * Right);
private:
};

ASTNode.cpp:

#ifndef AST_H
#define AST_H
#include "ASTNode.hpp"
#endif
ASTNode::ASTNode(ASTNodeType type)
{
Type = type;
Left = NULL;
Right = NULL;
}
ASTNode::ASTNode()
{
Type = ASTNodeType::UNDEFINED;
Left = NULL;
Right = NULL;
}
void ASTNode::setType(ASTNodeType Type)
{
Type = Type;
}
void ASTNode::setLeftChild(ASTNode * Left)
{
Left = Left;
}
void ASTNode::setRightChild(ASTNode * Right)
{
Right = Right;
}

AddExprNode.hpp:

#ifndef AST_H
#define AST_H
#include "ASTNode.hpp"
#endif
#include <string>
class AddExprNode : public ASTNode
{
public:
std::string add_op;
//AddExprNode() : ASTNode(){};
AddExprNode(std::string inputOp, ASTNodeType type);
std::string getOp();
};

AddExprNode.cpp:

#ifndef AST_H
#define AST_H
#include "AddExprNode.hpp"
#endif
#include <string>
AddExprNode::AddExprNode(std::string inputOp, ASTNodeType type) : ASTNode::ASTNode(type){
add_op = inputOp;
//Type = type;
}
std::string AddExprNode::AddExprNode::getOp(){
return add_op;
}

您没有正确使用包含防护。 保护的定义属于 .h 文件,而不是包含它的文件。

AddExprNode.cpp 定义AST_H符号。 AddExprNode.hpp 看到符号已经定义,因此它不包括ASTNode.hpp。 这会导致在使用它时未定义ASTNodeType