Chcę zaimplementować prostą strukturę danych drzewa wyrażeń arytmetycznych w języku C++, tak aby obiekt drzewa wyrażeń został zainicjowany przez: ExprTree(operator, expression1, expression2)
. Oto przykład jak to powinno działać:Struktura danych drzewa ekspresji
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
Oto jak mój kod wygląda tak daleko:
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();
}
Jednak uzyskać ten błąd podczas kompilacji kodu:
left of '->write' must point to class/struct/union/generic type
Byłbym wdzięczny, gdyby ktoś pomógł mi z tym błędem i ewentualnie podać kilka wskazówek, w jaki sposób powinienem wdrożyć tę strukturę danych. Btw, jestem bardzo nowy w C++.
Nie widzę odpowiedniego fragmentu kodu (wezwanie do "zapisu" lub jego definicji). – Unimportant
Edytowałem kod. Powinien przeczytać 'str' zamiast' write'. – Randolph
Musisz dodać typ szablonu podczas tworzenia obiektu: 'ExprTree expr1 ('*', x, y);' Następny wiersz 'ExprTree ('-', expr1, z)' wymaga konstruktora, który może podjąć 2 różne typy operandów. –
Unimportant