我目前正在使用玩具语言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;
}
答案 0 :(得分:2)
您没有正确使用包含保护。保护的定义属于.h文件,而不是包含它的文件。
AddExprNode.cpp定义AST_H
符号。 AddExprNode.hpp可以看到该符号已经定义,因此它不包含ASTNode.hpp。这会导致ASTNodeType
在您使用时未被定义。