[C++] Detailed explanation of Struct usage

 1. Basic usage of C Strcut

Several ways to declare structures in C language

struct structure name
{     data type variable name 1; };

The data types can be agreed data types such as int, char, float, etc., or they can be structure types (which have been defined before defining the structure here).
For example:

struct student
{
    char name[20];
    int id;
    float chinese;
    float english;
    float math;
};

Structure call:

struct structure structure name;
structure name. variable name = 

For example:

struct student s1;
s1.id = 20191028456;
s1.math = 95;

2. Basic usage of C++ Strcut

The C++ language treats structs as classes, so C++ structs can contain everything in a C++ class, such as constructors, destructors, friends, etc.

One obvious difference from struct in C is that C++ allows the keyword struct to be omitted when declaring structure variables.

struct student

{

    char name[20];

    int id;

    float chinese;

    float english;

    float math;

};
student s2;

s2.id = 20191031256;

s2.math = 60;

C++ also supports other centralized structure definition methods

1. Declare the structure variables at the same time when defining the structure.

struct student

{

    char name[20];

    int id;

    float chinese;

    float english;

    float math;

}st3,st4;

2. Omit the structure name and declare the structure variables

struct

{

    char name[20];

    int id;

    float chinese;

    float english;

    float math;

}st5;

In this way, you can also use st5.id to access members, but this type has no name. You cannot use names to create structure variables of this type, and it is not recommended.

3. typedef definition structure

You don't need to write struct when using typedefdefinition, which is much more convenient when defining variables.
For example:

typedef struct student
{
    char name[20];
    int id;
    float chinese;
    float english;
    float math;
}student_inf;

When used, it can be used directly student_infto define variables, such as:

    student_inf s1;
    s1.chinese = 95;
    s1.id = 1;

Guess you like

Origin blog.csdn.net/qq_35902025/article/details/129846178