用c++上下文无关语言的代码
时间: 2024-05-03 11:19:05 浏览: 74
以下是一个简单的C++上下文无关语言的代码示例,实现了一个简单的语法分析器来解析带有加法和乘法的表达式:
```c++
#include <iostream>
#include <string>
using namespace std;
// 定义语法树节点
class Node {
public:
virtual int eval() = 0;
};
// 定义数字节点
class NumNode : public Node {
public:
NumNode(int num): num(num) {}
int eval() { return num; }
private:
int num;
};
// 定义加法节点
class AddNode : public Node {
public:
AddNode(Node* left, Node* right): left(left), right(right) {}
int eval() { return left->eval() + right->eval(); }
private:
Node* left;
Node* right;
};
// 定义乘法节点
class MulNode : public Node {
public:
MulNode(Node* left, Node* right): left(left), right(right) {}
int eval() { return left->eval() * right->eval(); }
private:
Node* left;
Node* right;
};
// 定义语法分析器
class Parser {
public:
Parser(string expr): expr(expr), pos(0) {}
Node* parse() {
Node* left = parseTerm();
while (pos < expr.length()) {
char op = expr[pos];
if (op != '+' && op != '*') {
throw runtime_error("Invalid operator");
}
pos++;
Node* right = parseTerm();
if (op == '+') {
left = new AddNode(left, right);
} else {
left = new MulNode(left, right);
}
}
return left;
}
private:
Node* parseTerm() {
if (pos >= expr.length()) {
throw runtime_error("Unexpected end of expression");
}
if (isdigit(expr[pos])) {
return parseNum();
} else if (expr[pos] == '(') {
pos++;
Node* node = parse();
if (pos >= expr.length() || expr[pos] != ')') {
throw runtime_error("Missing closing parenthesis");
}
pos++;
return node;
} else {
throw runtime_error("Invalid term");
}
}
Node* parseNum() {
int num = 0;
while (pos < expr.length() && isdigit(expr[pos])) {
num = num * 10 + (expr[pos] - '0');
pos++;
}
return new NumNode(num);
}
string expr;
int pos;
};
int main() {
string expr = "2*3+4";
Parser parser(expr);
Node* root = parser.parse();
int result = root->eval();
cout << result << endl; // 输出 10
return 0;
}
```
示例中的语法分析器能够解析一些简单的表达式,并且使用了上下文无关语言的思想来实现语法分析。
阅读全文