Programmazione orientata agli oggetti in ANSI-C. Programmazione Savvy. Aritmetica

Se vogliamo eseguire operazioni aritmetiche, dobbiamo fare in modo che la funzione che si occupa dell'esecuzione restituisca valori double da stampare nella funzione process().

static double exec (const void * tree)
{
return (* (struct Type **) tree) —> exec(tree);
}
void process (const void * tree)
{
printf("\t%g\n", exec(tree));
}

Per ogni tipo di nodo, abbiamo bisogno di una funzione che effettui i calcoli e restituisca il valore del nodo. Ecco due esempi:

static double doVal (const void * tree)
{
return ((struct Val *) tree) —> value;
}
static double doAdd (const void * tree)
{
return exec(((struct Bin *) tree) —> left) +
exec(((struct Bin *) tree) —> right);
}
static struct Type _Add = { mkBin, doAdd, freeBin };
static struct Type _Value = { mkVal, doVal, free };
const void * Add = & _Add;
const void * Value = & _Value;
Scarica subito una copia gratis

Scrivi un commento

Seguici anche sul tuo Social Network preferito!

Send this to a friend