The most complete and detailed explanation of C++ structure (struct)

1. Definition and Declaration

1. Define the structure type first and then define the variable separately

struct Student
{
    int Code;
    char Name[20];
    char Sex;
    int Age;
};
struct Student Stu;
struct Student StuArray[10];
struct Student *pStru;

The structure type is struct Student, so neither struct nor Student can be omitted. But in fact, when I use codeblocks to run, the definition of the following variables is also possible without adding struct.

2. Define immediately after the structure type declaration

struct Student
{
    int Code;
    char Name[20];
    char Sex;
    int Age;
}Stu,StuArray[10],*pStu;

In this case, structure variables can be defined later.

3. Direct definition while declaring an unnamed structure variable

struct
{
    int Code;
    char Name[20];
    char Sex;
    int Age;
}Stu,Stu[10],*pStu;

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

4. Use typedef to declare a structure variable and then use 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;

Student is a specific structure type, uniquely identified. There is no need to add struct here

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 accessing, the ordinary structure variable uses the member variable access symbol ".", and the pointer type structure variable uses the member variable access symbol "->".

  • Note: Don’t forget to delete the dynamically created structure variables after use.
#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;
}

Second, the structure constructor

Three methods of structure initialization:

  • 1. Use the default constructor that comes with the structure
  • 2. Use the constructor with parameters
  • 3. Use the default parameterless constructor

Key points: Do not write anything is to use the default constructor that comes with the structure. If you rewrite the constructor with parameters, an error will occur if you do not pass in parameters when initializing the structure. When creating a structure array, if only the constructor with parameters is written, an error that the array cannot be initialized will occur! ! ! The following is an example of a safer structured structure

struct node{
    int data;
    string str;
    char x;
    //注意构造函数最后这里没有分号哦!
  node() :x(), str(), data(){} //无参数的构造函数数组初始化时调用
  node(int a, string b, char c) :data(a), str(b), x(c){}//有参构造
};
//结构体数组声明和定义
struct node{
    int data;
    string str;
    char x;
    //注意构造函数最后这里没有分号哦!
  node() :x(), str(), data(){} //无参数的构造函数数组初始化时调用
  node(int a, string b, char c) :data(a), str(b), x(c){}//初始化列表进行有参构造
}N[10];

3. Structure nesting

Just as objects of one class can be nested within another class, instances of a struct can be nested within another struct. For example, consider the following declaration:

struct Costs
{
    double wholesale;
    double retail;
};

struct Item
{
    string partNum;
    string description;
    Costs pricing;
}widget;

The Costs structure has two double members, wholesale and retail. Item structure has 3 members, the first 2 are partNum and description, they are all string objects. The third is pricing, which is a nested Costs structure. If an Item structure named widget is defined, Figure 3 illustrates its members.

How to access nested structures:

widget.partnum = "123A";
widget.description = "iron widget";
widget.pricing.wholesale = 100.0;
widget.pricing.retail = 150.0;

4. Structure assignment and access

    • Assignment
      The easiest way to initialize a member of a structure variable is to use an initializer list. An initialization list is a list of values ​​used to initialize a set of memory locations. Items in the list are separated by commas and enclosed in braces.
struct Date
{
  int day, month, year;
};

The declaration defines that birthday is a variable of the Date structure, and the values ​​in curly braces are assigned to its members in sequence. So the data member of birthday has been initialized, as shown in Figure 2.

It is also possible to initialize only some members of a structure variable. For example, if you only know that the birthday you want to store is August 23, but not the year, you can define and initialize a variable as follows:

Date birthday = {23,8};

Here only the day and month members are initialized, and the year member is not initialized. However, if a struct member is uninitialized, all members following it need to remain uninitialized. C++ does not provide a way to skip members when using initializer lists. The following statement attempts to skip initialization of the month member. This is not legal.

Date birthday = {23,1983}; //非法

It is also important to note that structure members cannot be initialized in a structure declaration, because a structure declaration just creates a new data type, and variables of this type do not yet exist. For example, the following declarations are illegal:

//非法结构体声明
struct Date
{
    int day = 23,
    month = 8,
    year = 1983;
};

Because a struct declaration only declares what a struct "looks like", no member variables are created in memory. Only by instantiating a struct by defining a variable of that struct type will there be a place to store the initial value.

  • access

Define the structure:

struct MyTree{
    MyTree*left;
    MyTree*right;
    int val;
    MyTree(){}
    MyTree(int val):left(NULL),right(NULL),val(val){}
};

General structure variable access method:

int main(){

    MyTree t;
    t.val = 1;
    cout<<t.val;

    return 0;
}

It can be seen that the variables in the structure can be accessed directly through the "." operator.

As for the structure pointer: the variable of the structure pointed to by the pointer must be accessed through the "->" symbol.

int main(){

    MyTree *t1 = new MyTree(1);
    MyTree *t2 ;
    t2->val = 2;
    cout<<t1->val<<" "<<t2->val;  //输出:1 2
    t2.val = 3;  //error: request for member 'val' in 't2', whitch is of pointer type 'MyTree*' (maybe you meant to use '->' ?)
    cout<<t2.val;  //error: request for member 'val' in 't2', which is of pointer type 'MyTree*' (maybe you mean to use '->' ?
    return 0;
}

Benefits of this article, free C++ learning package, technical video/code, 1000 Dachang interview questions, including (C++ basics, network programming, database, middleware, back-end development, audio and video development, Qt development)↓↓↓ ↓↓↓See below↓↓Click at the bottom of the article to get it for free↓↓

Guess you like

Origin blog.csdn.net/m0_60259116/article/details/132190233