Zadania
-
any.h
,any.c
: stwórz bibliotekę, która definiuje typany
pozwalający na przechowanie wielu różnych typów:-
typedef struct any { /* zdefiniowane przez osobę studencką */ } any_t;
, które zawiera ręcznie stworzoną vtable -
any_t any_from_int(int x);
- funkcja tworząca wartość any z wartości liczbowej -
any_t any_from_str(char const* s);
- funkcja tworząca wartość any z ciągu znaków -
any.length(any);
- zwraca długość reprezentacji dziesiętnej dla liczby, długość łańcucha dla ciągu znaków -
any.free(any);
- czyszczące zaalokowaną pamięć jeśli taka była potrzebna -
any.print(any);
- wypisujące wartość na standardowe wyjście (wraz z znakiem nowej linii)
-
Przykład vtable
#include <stdio.h>
#include <math.h>
typedef struct shape {
union
{
struct
{
float radius;
};
struct
{
float width, height;
};
};
// vtable:
float (*area)(struct shape *this);
void (*print)();
} shape;
float circle_area(struct shape *this)
{
return M_PI * this->radius * this->radius;
}
shape circle(float r)
{
struct shape s;
s.radius = r;
s.area = circle_area;
return s;
}
float rect_area(struct shape *this)
{
return this->width * this->height;
}
shape rectangle(float w, float h)
{
struct shape s;
s.width = w;
s.height = h;
s.area = rect_area;
return s;
}
int main()
{
shape s = rectangle(10, 20);
printf("Area is: %f\n", s.area(&s));
return 0;
}