cppannotations/yo/intro/struct.yo
2009-10-11 18:25:29 +00:00

52 lines
2.4 KiB
Text

In bf(C++) we may define i(functions as members of structs). Here we
encounter the first concrete example of an object: as previously described
(see section ref(OOP)), an i(object) is a structure containing data while
specialized functions exist to manipulate those data.
A definition of a tt(struct Point) is provided by the code fragment below.
In this structure, two tt(int) data fields and one function tt(draw) are
declared.
verb(
struct Point // definition of a screen-dot
{
int x; // coordinates
int y; // x/y
void draw(); // drawing function
};
)
A similar structure could be part of a painting program and could, e.g.,
represent a pixel. With respect to this tt(struct) it should be noted that:
itemization(
it() The function tt(draw) mentioned in the tt(struct) definition is a
mere em(declaration). The actual code of the function defining the actions
performed by the function is found elsewhere (the concept of functions inside
tt(struct)s is further discussed in section ref(FunctionsInStructs)).
it() The size of the tt(struct) tt(Point) is equal to the size of its
two tt(int)s. A function declared inside the structure does not affect its
size. The compiler implements this behavior by allowing the function
tt(draw) to be available only in the context of a tt(Point).
)
The tt(Point) structure could be used as follows:
verb(
Point a; // two points on
Point b; // the screen
a.x = 0; // define first dot
a.y = 10; // and draw it
a.draw();
b = a; // copy a to b
b.y = 20; // redefine y-coord
b.draw(); // and draw it
)
As shown in the above example a function that is part of the structure may
be selected using the dot (.) (the arrow (tt(->)) operator is used when
pointers to objects are available). This is therefore identical to the way
data fields of structures are selected.
The idea behind this syntactic construction is that several types may
contain i(functions having identical names). E.g., a structure representing a
circle might contain three tt(int) values: two values for the coordinates of
the center of the circle and one value for the radius. Analogously to the
tt(Point) structure, a tt(Circle) may now have a function tt(draw) to draw the
circle.