编写一段可运行的完整c++代码 要求: 1) 完成表达式类; 2) 完成中缀转后缀函数,完成后缀表达式的求值函数; 3) 完成函数判断中缀表达式是否合法(仅需考虑括号是否匹配)(考虑额外条件并测试正确
时间: 2024-10-24 16:13:13 浏览: 39
```cpp
#include <iostream>
#include <stack>
#include <string>
class Expression {
public:
virtual ~Expression() {}
virtual double evaluate() = 0; // 虚拟函数,用于计算表达式的值
};
class InfixToPostfix : public Expression {
private:
std::string expression;
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/') && !std::isdigit(c);
}
int precedence(char op) {
if (op == '(') return 0;
if (op == ')') return 100;
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return -1;
}
public:
void setExpression(const std::string& e) { expression = e; }
double evaluate() override {
std::stack<char> operators;
std::string postfix;
for (char c : expression) {
if (!isOperator(c)) {
postfix += c;
} else {
while (!operators.empty() && precedence(operators.top()) >= precedence(c)) {
postfix += operators.pop();
}
operators.push(c);
}
}
while (!operators.empty()) {
postfix += operators.pop();
}
return evaluatePostfix(postfix);
}
static double evaluatePostfix(const std::string& postfix) {
double num = 0;
char prev_char = '+';
for (char c : postfix) {
if (std::isdigit(c)) {
num = num * 10 + c - '0';
} else {
switch (prev_char) {
case '+': num += static_cast<int>(c); break;
case '-': num -= static_cast<int>(c); break;
case '*': num *= static_cast<int>(c); break;
case '/':
if (c == '/') throw "Division by zero error";
num /= static_cast<int>(c);
break;
}
prev_char = c;
}
}
return num;
}
};
bool isValidExpression(const std::string& expression) {
std::stack<char> brackets;
for (char c : expression) {
if (c == '(') brackets.push('(');
else if (c == ')') {
if (brackets.empty()) return false;
brackets.pop();
}
}
return brackets.empty();
}
int main() {
InfixToPostfix expr("A + B * C");
expr.setExpression(expr.expression);
try {
double result = expr.evaluate();
std::cout << "Infix to Postfix: " << expr.expression << " = " << result << std::endl;
std::cout << "Is valid? " << (isValidExpression(expr.expression) ? "Yes" : "No") << std::endl;
} catch (const char* msg) {
std::cerr << "Error: " << msg << std::endl;
}
return 0;
}
```
这段代码首先定义了一个`Expression`基类和`InfixToPostfix`类,实现了中缀表达式到后缀表达式的转换以及后缀表达式的求值。然后,`isValidExpression`函数用于检查括号是否匹配,是否构成有效的中缀表达式。在`main`函数中,我们创建一个`InfixToPostfix`实例,并验证其结果及有效性。
注意:这个代码假设后缀表达式只包含整数和基本运算符,且不处理除零的情况。实际应用中可能需要添加更多的异常处理和类型检查。
阅读全文