gpt4 book ai didi

c++ - union c++ yacc 中的结构

转载 作者:行者123 更新时间:2023-11-28 05:40:31 24 4
gpt4 key购买 nike

我想在 yacc 文件中添加 union 结构,但我发现了这个错误:

"error : member 'Info YYSTYPE ::info' with constructor not allowed in union "

%{
#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 中,因为编译器无法判断要构造或析构哪个 union 成员。

一种替代方法是在 union 中使用指针:

%union {
...
Info *info;
};

在这种情况下,如果/当不再需要指针时,您需要小心明确地删除它们。 Bison 的 %destructor 在这里很有用,可以在出现错误时避免泄漏。

或者,根本不使用 %union -- 只需将 YYSTYPE 定义为单一类型:

%{
#define YYSTYPE struct Info
%}

在这种情况下,您的所有规则都需要使用相同的类型(没有 %type 声明让不同的规则产生不同的东西)。如果你真的需要不同的类型,像 boost::variant 这样的东西会很有用..

关于c++ - union c++ yacc 中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37217643/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com