The parser itself is a large design model, with the focus on designing the parser itself. However, because the parser itself is difficult to design, the perfect parser mode is rarely used, however, the idea of this design pattern is not difficult.
The following is a simple and practical method for C ++ to implement the parser mode. If different Resolvers are used, different results will be parsed for the same content.
# Include <stdio. h ># include <string> using namespace STD; Class context {public: String cmd; void setcontext (string s) {cmd = s ;}}; class interpreterbase {protected: context * context; public: interpreterbase (Context * C): Context (c) {}// virtual void interpret () will not be able to parse External commands if it is not written = 0 (); virtual void interpret () = 0 ;}; class interpreterincre: Public interpreterbase {public: interpreterincre( context * C): interpreterbase (c) {} void interpret () {string cmd = context-> cmd; For (INT I = 0; I <(INT) cmd. size (); I ++) {putchar (CMD [I] + 1);} putchar ('\ n') ;}}; class interpreterdere: Public interpreterbase {public: interpreterdere (Context * C): interpreterbase (c) {} void interpret () {string cmd = context-> cmd; For (INT I = 0; I <(INT) cmd. size (); I ++) {putchar (CMD [I]-1) ;}putchar ('\ n') ;}; int main () {context; context. setcontext ("abcdefg"); interpreterdecredere (& context); interpreterincreinre (& context); Decret. interpret (); incret. interpret (); Return 0 ;}
The running result returns different results for the same string abcdefg using different Resolvers:
It can be said that the C \ c ++ compiler is written using this design mode. It is of course difficult to improve the implementation of such a parser.