|
Combining variables with struct
A
struct is a way to collect
a group of variables into a structure. Once you create a struct, then you
can make many instances of this “new” type of variable you’ve
invented. For example:
//: C03:SimpleStruct.cpp
struct Structure1 {
char c;
int i;
float f;
double d;
};
int main() {
struct Structure1 s1, s2;
s1.c = 'a'; // Select an element using a '.'
s1.i = 1;
s1.f = 3.14;
s1.d = 0.00093;
s2.c = 'a';
s2.i = 1;
s2.f = 3.14;
s2.d = 0.00093;
} ///:~
The struct declaration must end
with a semicolon. In main( ), two instances of Structure1 are
created: s1 and s2. Each of these has their own separate versions
of c, i, f, and d. So s1 and s2
represent clumps of completely independent variables. To select one of the
elements within s1 or s2, you use a ‘.’, syntax
you’ve seen in the previous chapter when using C++ class objects
– since classes evolved from structs, this is where that
syntax arose from.
One thing you’ll notice is the
awkwardness of the use of Structure1 (as it turns out, this is only
required by C, not C++). In C, you can’t just say Structure1 when
you’re defining variables, you must say struct Structure1. This is
where typedef becomes especially handy in C:
//: C03:SimpleStruct2.cpp
// Using typedef with struct
typedef struct {
char c;
int i;
float f;
double d;
} Structure2;
int main() {
Structure2 s1, s2;
s1.c = 'a';
s1.i = 1;
s1.f = 3.14;
s1.d = 0.00093;
s2.c = 'a';
s2.i = 1;
s2.f = 3.14;
s2.d = 0.00093;
} ///:~
By using
typedef in this way, you can pretend (in C; try
removing the typedef for C++) that Structure2 is a built-in type,
like int or float, when you define s1 and s2 (but
notice it only has data – characteristics – and does not include
behavior, which is what we get with real objects in C++). You’ll notice
that the struct identifier has been left off at the beginning, because
the goal is to create the typedef. However, there are times when you
might need to refer to the struct during its definition. In those cases,
you can actually repeat the name of the struct as the struct name
and as the typedef:
//: C03:SelfReferential.cpp
// Allowing a struct to refer to itself
typedef struct SelfReferential {
int i;
SelfReferential* sr; // Head spinning yet?
} SelfReferential;
int main() {
SelfReferential sr1, sr2;
sr1.sr = &sr2;
sr2.sr = &sr1;
sr1.i = 47;
sr2.i = 1024;
} ///:~
If you look at this for awhile,
you’ll see that sr1 and sr2 point to each other, as well as
each holding a piece of data.
Actually, the struct name does not
have to be the same as the typedef name, but it is usually done this way
as it tends to keep things simpler.
|
|