I. Definitions and declarations

1. Define the structure type first and then do the variable definition separately

struct Student
{
    int Code;
    char Name[20];
    char sex;
    int age;
};

struct Student Stu;
struct Student StuArray[20];
struct Student *pStru;
Copy the code

The struct type is struct Student, so neither struct nor Student can be omitted.

2. Define immediately after the struct type description

struct Student
{
    int code;
    char name[20];
    char sex;
    int age;
}Stu, StuArray[20], *pStu;
Copy the code

In this case, you can continue to define struct variables later.

3. Define an unnamed struct variable directly while specifying it

struct
{
    int code;
    char name[20];
    char sex;
    int age; 
}Stu, Stu[10], *pStu;
Copy the code

In this case, no other variables can be defined later.

4. Use a typedef to specify a structure variable followed by the new class name to define the variable

typedef struct
{
    int code;
    char name[20];
    char sex;
    int age;
}student;

student Stu, Stu[10], *pStu;
Copy the code

Student is a concrete structure type, unique identifier, no need to add struct

5. Use new to dynamically create structure variables

When using new to dynamically create a structure variable, it must be a structure pointer type.

When accessed, normal structure variables use the member variable accessor “.” structure variables of pointer type use the member variable accessor “->”

Note: Do not forget delete after using dynamically created structure variables

#include <iostream>

using namespace std;

struct Student
{
    int code;
    char name[20];
    char sex;
    int age;
}Stu, StuArray[10], *pStu;

int main()
{
    Student *s = new Student(); // Student *s = new Student;
    
    s->code = 1;
    cout << s->code;
    
    delete s;
    return 0;
}
Copy the code

Note: defined in the function, only the function can access.

Struct constructors

Three struct initialization methods

1. Use the default constructor that comes with the structure

2. Use a constructor that takes arguments

3. Use the default no-parameter constructor

Three, structure nesting

A structure can be nested within another structure.

struct Costs
{
    double wholesale;
    double retail;
};

struct Item
{
    string partNum;
    string description;
    Costs pricing;
}widget;
Copy the code

How a nested structure is accessed

widget.partnum = "1234A"; widget.description = "Iron"; Widget. Pricing. Wholesale = 100.0; Widget. Pricing. Retail = 150.0;Copy the code