C++ 将父类对象强制转换为子类时出现问题

C++ 将父类对象强制转换为子类时出现问题,c++,casting,bison,micro,C++,Casting,Bison,Micro,我目前正在为玩具语言“Micro”实现一个编译器,并创建了一些类来处理AST。我使用的解析器工具是Bison。我正试图为while循环和if/else语句生成汇编,但在将父类对象ASTNode转换为其子对象WhileNode时遇到了问题 在解析器中,我将所有这些节点的返回类型声明为父类ASTNode %type <node> if_stmt stmt base_stmt loop_stmt read_stmt write_stmt control_stmt return_stmt a

我目前正在为玩具语言“Micro”实现一个编译器,并创建了一些类来处理AST。我使用的解析器工具是Bison。我正试图为while循环和if/else语句生成汇编,但在将父类对象ASTNode转换为其子对象WhileNode时遇到了问题

在解析器中,我将所有这些节点的返回类型声明为父类ASTNode

%type <node> if_stmt stmt base_stmt loop_stmt read_stmt write_stmt control_stmt return_stmt assign_stmt else_part while_stmt func_decl

%union{
  std::string* s;
  std::list<std::string> * str_list;
  ASTNode * node;
  std::list<ASTNode*> * ast_list;
  JumpType * jtype;
  Conditional * condition;
}
%在执行函数时键入if stmt stmt base\u stmt loop\u stmt read\u stmt write\u stmt control\u stmt return\u stmt assign\u stmt else\u part
%联合{
std::string*s;
标准::列表*str_列表;
ASTNode*节点;
std::list


我使用动态_cast的原因是因为返回类型是ASTNode,所以它没有子方法copyStmtList()。如果您能帮我改进此强制转换方法,我将不胜感激!

好吧,我是个傻瓜。我没有意识到我无意中将“*$7”中的“$”替换为“*$7”,在这种情况下,尝试使用*7执行任何操作都只是取消对int类型的引用(这显然是无效的)我为这个错误道歉。

这也不是您编写dynamic_cast的方式;您需要括号。碰巧,bison会将$6的扩展插入括号,但您不应该依赖于此。
while_stmt      : _WHILE _OPAREN cond _CPAREN decl 
                { 
                  currentBlockID = scope_iterator;
                  SymbolTable* tmp = new SymbolTable("BLOCK " + std::to_string(scope_iterator++), ststack.top());
                  ststack.top()->children.push_back(tmp);
                  ststack.push(tmp);
                  $<node>$ = new WhileNode($3->left_expr, $3->right_expr, currentBlockID, $3->jtype, ASTNodeType::WHILE);
                } 
                stmt_list _ENDWHILE  
                {  
                  ststack.pop(); 
                  dynamic_cast<WhileNode *> $<node>6->copyStmtList(*7);
                  $$ = $<node>6;
                }
                ;
src/parser.yy: In function ‘int yyparse()’:
src/parser.yy:388:81: error: invalid type argument of unary ‘*’ (have ‘int’)
                   dynamic_cast<WhileNode *> $<node>6->copyStmtList(*7);