我想在yacc文件中的联合中添加结构,但发现此错误:
“错误:在联合中不允许使用构造函数的成员'Info YYSTYPE :: info'成员”
%{
#include <cstdio>
#include <iostream>
using namespace std;
extern "C" int yylex();
extern "C" int yyparse();
extern "C" FILE *yyin;
struct Info{ int intval; float floatval; string stringval ;int type; }
void yyerror(const char *s);
%}
%union {
int ival;
float fval;
char *sval;
struct Info info;
}
最佳答案
您不能将非POD结构放入C ++的联合中,因为编译器无法告知要构造或销毁哪个联合成员。
一种替代方法是在联合中使用指针:
%union {
...
Info *info;
};
在这种情况下,如果/不再需要指针,则需要谨慎地显式删除它们。在有错误的情况下,Bison的
%destructor
可以在这里用于避免泄漏。或者,根本不使用
%union
,只需将YYSTYPE
定义为单个类型:%{
#define YYSTYPE struct Info
%}
在这种情况下,您的所有规则都需要使用相同的类型(没有
%type
声明可以使不同的规则产生不同的结果)。如果确实需要使用其他类型,则类似boost::variant
的内容可能会有用。关于c++ - union c++ yacc中的struct,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37217643/