WORKING WITH STRUCTURES


Structures are yet another way of organizing the data within your code. They give you the ability to create new data types composed of existing ones, or even ones you create. Their main benefit is that they keep related data together, which helps not only in keeping your program clear, but in performing data manipulation.

The basic component of a structure uses the struct keyword, followed by the name of the new composite data type you created, and then braces. Within the braces, you specify the data types that you want the structure to be composed of. Although a structure uses braces like a function or control structure, because it is a data type, the braces must be followed by a semicolon.

Here is one example of a structure:

 struct UserType {     Int16 IDCode;     //User code     Boolean fActive; //Current status }; 

The elements within this structure are known as the members of the structure. After you've created this structure, you're free to use it as you would a fundamental or custom enumerated type you've created. For instance, you can declare a single instance of the new type or an entire array of the following:

 UserType admin; UserType subscribers[1000]; 

This code creates a single player and an array of 1,000 subscribers.

Unlike fundamental data types such as Intl6 or Single, however, you must access the members of your struct type individually. To access the elements of a structure, you use the access specifier, which is a period between the structure variable's name and the member you want to access:

 player.fAlive = true; user.IDCode = 1000; 

Structures can even be composed of other structures. This allows you to create even more complex data types. For instance:

 struct CoordType {     Int16 x, y, z; }; struct VehicleType {     struct CoordType coordinates;     Int16 hullIntegrity;     Single velocity; }; 

In this example, the VehicleType structure uses a presumably widely used utility structure for storing coordinates in a game world. The coordinates can be initialized in this way:

 VehicleType playerVehicle; playerVehicle.coordinates.x = 0; playerVehicle.coordinates.y = 0; userVehicle.coordinates.z = 0; 




Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner 2006
ISBN: 735615381
EAN: N/A
Year: 2005
Pages: 131

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net