A struct is a structure that can contain different data types. It is a data type that can be defined by itself. Its features are different from those of arrays, first, struct can declare different data types in a structure. Second, struct variables with the same structure can be assigned values to each other, but arrays cannot, because an array is a data set of a single data type, it is not a data type (while a struct is), and the array name is a constant pointer, it cannot be used as a left value for computation, therefore, arrays cannot be duplicated by array names, even if the data type and array size are identical.
Define the struct using the struct modifier, for example:
struct test { float a; int b; };
The code above defines a struct named test. Its data type is test. It contains two members, A and B. The data type of member A is floating point, the data type of member B is integer. Since struct itself is a custom data type, the method for defining struct variables is the same as that for defining common variables. Test pn1; in this way, the pn1 struct variable of the test struct data type is defined. The access of struct members is carried out through the vertex operator, pn1.a = 10: assign a value to Member a of the struct variable pn1. Note: When the struct is declared, it does not occupy any memory space, the computer allocates memory only when you define the struct variable with the struct type you have defined.
Struct can also define pointers. struct pointers are called structure pointers. The structure pointer uses the-> symbol to access members. The following is a complete example of the above description:
# Include <iostream> # include <string> using namespace STD; struct test // defines a struct {int A; // defines the struct member A int B; // define struct member B}; void main () {test pn1; // define struct variable pn1 test pn2; // define struct variable pn2 pn2.a = 10; // use the member operator. assign pn2. B = 3 to member A in struct variable pn2; // use the member operator. assign pn1 = pn2 to member B in struct variable pn2; // copy all the Member values of pn2 to the pn1 cout variable with the same structure <pn1.a <"|" <pn1. B <Endl; cout <pn2.a <"|" <pn2. B <Endl; test * point; // defines the structure pointer point = & pn2; // pointer pointing to the memory address cout of the struct variable pn2 <pn2.a <"|" <pn2. B <Endl; point-> A = 99; // use the structure pointer to modify the cout value of pn2 member A <pn2.a <"|" <pn2. B <Endl; cout <point-> A <"|" <point-> B <Endl; cin. get ();}