Composite type
From Wikipedia, the free encyclopedia
|
In computer science, composite types are datatypes which can be constructed in a programming language out of that language's primitive types and other composite types. The act of constructing a composite type is known as composition.
C/C++ structures and classes
A In C++, the only difference between a Note that while classes and the DeclarationA For example: <source lang="c">
struct Account {
int account_number;
char *first_name;
char *last_name;
float balance;
};
</source> defines a type, referred to as Since writing
typedef struct Account_ {
int account_number;
char *first_name;
char *last_name;
float balance;
} Account;
</source> In C++ code, the As another example, a three-dimensional Vector composite type that uses the floating point data type could be created with: <source lang="c">
struct Vector {
float x;
float y;
float z;
};
</source> A variable named Likewise, a color structure could be created using: <source lang="c">
struct Color {
int red;
int green;
int blue;
};
</source> In 3D graphics, you usually must keep track of both the position and color of each vertex. One way to do this would be to create a
struct Vertex {
Vector position;
Color color;
};
</source> InstantiationCreate a variable of type Member accessAssign values to the components of v.position.x = 0.0; v.position.y = 1.5; v.position.z = 0.0; v.color.red = 128; v.color.green = 0; v.color.blue = 255; Primitive SubtypingThe primary use of
struct ifoo_old_stub {
long x, y;
};
struct ifoo_version_42 {
long x, y, z;
char *name;
long a, b, c;
};
void operate_on_ifoo(struct ifoo_old_stub *);
struct ifoo_version_42 s;
. . .
operate_on_ifoo(&s);
will work correctly. Function typesFunction types (or type signatures) are constructed from primitive and composite types, and can serve as types themselves when constructing composite types: <source lang="C"> typedef struct { int x; int y; } Point; typedef double (*Metric) (Point p1, Point p2); typedef struct { Point centre; double radius; Metric metric; } Circle; </source> See also |


