Voglio implementare una struttura di dati dell'albero delle espressioni aritmetiche semplice in C++, in modo tale che un albero di espressioni sia inizializzato da: ExprTree(operator, expression1, expression2)
. Ecco un esempio di come dovrebbe funzionare:Struttura dati dell'albero di espressione
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
Ecco come il mio codice è finora:
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();
}
Tuttavia, ottengo questo errore quando compilo il codice:
left of '->write' must point to class/struct/union/generic type
Apprezzerei se qualcuno mi aiutasse con questo errore e possibilmente fornire alcuni suggerimenti su come dovrei implementare questa struttura dati. Btw, sono molto nuovo di C++.
Non vedo il pezzo di codice rilevante (la chiamata a 'write' o la sua definizione). – Unimportant
Ho modificato il codice. Dovrebbe leggere 'str' invece di' write'. – Randolph
È necessario aggiungere il tipo di modello quando si crea un'istanza dell'oggetto: 'ExprTree expr1 ('*', x, y);' La riga successiva 'ExprTree ('-', expr1, z)' richiede un costruttore che può prendere 2 tipi diversi di operandi. –
Unimportant