我希望您能在C++中实现一个简单的算术表达式树数据结构,使得一个表达式树对象可以通过以下方式进行初始化:
然而,当我编译代码时,会出现以下错误:
ExprTree(operator, expression1, expression2)
。以下是它应该如何工作的示例:double x = 1, y = 2, z = 0.5;
expr1 = ExprTree('*', x, y); // expr1 = 1 * 2 = 2
expr2 = ExprTree('-', expr1, z); // expr2 = (1 * 2) - 0.5 = 1.5
cout << expr2.str() << endl; // ((1 * 2) - 0.5)
cout << expr2.eval() << endl; // 1.5
这是目前我的代码的样子:
template<class operand_type>
class ExprTree
{
public:
ExprTree(const char op_, operand_type& operand1_, operand_type& operand2_)
{
op = op_;
operand1 = operand1_;
operand2 = operand2_;
}
double eval() const;
std::string str() const;
private:
char op;
typename operand_type operand1, operand2;
};
template<class operand_type>
std::string ExprTree<operand_type>::str() const
{
std::ostringstream os;
std::string op1, op2;
if (typeid(*operand1) == typeid(ExprTree))
op1 = operand1->str();
else
op1 = std::string(*operand1);
if (typeid(*operand2) == typeid(ExprTree))
op2 = operand1->str();
else
op2 = std::string(*operand2);
os << "(" << op1 << " " << op << " " << op2 << ")";
return os.str();
}
然而,当我编译代码时,会出现以下错误:
left of '->write' must point to class/struct/union/generic type
希望有人能够帮助我解决这个错误,并提供一些关于如何实现这个数据结构的技巧。顺便说一句,我对c ++非常陌生。
write
或者它的定义)。 - UnimportantExprTree<double> expr1('*', x, y);
下一行ExprTree('-', expr1, z)
需要一个可以接受两个不同类型操作数的构造函数。 - Unimportantif (typeid(*operand1) == typeid(ExprTree))
非常糟糕。你应该使用虚函数。 - Martin York