如何在 C++ 中使用 yyextra?

How to use yyextra in C++?

我想在扫描程序规则内访问外部结构。在使用 C 语言时,提供了 yyextra 作为解决方案。显然 yyextra 在生成 C++ 扫描器时不可用。 实现相同目标的正确解决方案是什么?

您可以从 yyFlexLexer 派生出您自己的词法分析器 class 并向其中添加您想要的任何内容。

如果你这样做,你可能想告诉 Flex 你的名字 class:

%option yyclass="myLexer"

参见this option的描述:

‘--yyclass=NAME, %option yyclass="NAME"’
…informs flex that you have derived NAME as a subclass of yyFlexLexer, so flex will place your actions in the member function NAME::yylex() instead of yyFlexLexer::yylex().…

note about the yylex()成员函数:

virtual int yylex()
performs the same role is yylex() does for ordinary flex scanners: it scans the input stream, consuming tokens, until a rule’s action returns a value. If you derive a subclass S from yyFlexLexer and want to access the member functions and variables of S inside yylex(), then you need to use %option yyclass="S" to inform flex that you will be using that subclass instead of yyFlexLexer. In this case, rather than generating yyFlexLexer::yylex(), flex generates S::yylex() (and also generates a dummy yyFlexLexer::yylex() that calls yyFlexLexer::LexerError() if called).