C++ Structure (struct)

C/C++ arrays allow defining variables that can store data items of the same type, butStructureis another user-defined available data type in C++, which allows you to store data items of different types.

Structures are used to represent a record. Suppose you want to track the dynamics of books in a library; you may need to track the following attributes of each book:

  • Title: Title
  • Author: author
  • Subject: category
  • Book ID: the book's ID

Define structure

In C++, the struct statement is used to define a structure.

A structure is a user-defined data type used to combine data of different types. Similar to classes, structures allow you to define member variables and member functions.

To define a structure, you must usestructstatement. The struct statement defines a new data type containing multiple members; the format of the struct statement is as follows:

struct type_name { member_type1 member_name1; member_type2 member_name2; member_type3 member_name3; . . } object_names;

type_nameis the name of the structure type,member_type1 member_name1is a standard variable definition, for exampleint i;orfloat f;or other valid variable definitions. At the end of the structure definition, before the last semicolon, you can specify one or more structure variables; this is optional. The following declares a structure typeBooks, the variable isbook:

struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } book;

Advantages of structures:

  • Simple data encapsulation: suitable for encapsulating simple data of multiple types, usually used for data storage.
  • Lightweight: compared toclass, structure syntax is more concise and suitable for small data objects.
  • Object-oriented support: supports constructors, member functions, and access control, enabling object-oriented design.

Accessing structure members

To access the members of a structure, we useMember access operator (.). The member access operator is a period between the structure variable name and the structure member we want to access.

The following example demonstrates the use of structures:

Example

#include <iostream> #include <cstring> using namespace std; // Declare a struct type Books struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main( ) { Books Book1; // Define a variable Book1 of the struct type Books Books Book2; // Define a variable Book2 of the struct type Books // Book1 details strcpy( Book1.title, "C++ Tutorial"); strcpy( Book1.author, "Example"); strcpy( Book1.subject, "Programming language"); Book1.book_id = 12345; // Book2 details strcpy( Book2.title, "CSS Tutorial"); strcpy( Book2.author, "Example"); strcpy( Book2.subject, "Front-end technology"); Book2.book_id = 12346; // Output Book1 information cout << "First book title:" << Book1.title <<endl; cout << "First book author:" << Book1.author <<endl; cout << "First book category:" << Book1.subject <<endl; cout << "First book ID:" << Book1.book_id <<endl; // Output Book2 information cout << "Second book title:" << Book2.title <<endl; cout << "Second book author:" << Book2.author <<endl; cout << "Second book category:" << Book2.subject <<endl; cout << "Second book ID:" << Book2.book_id <<endl; return 0; }

The example defines the structure type Books and its two variables Book1 and Book2. When the above code is compiled and executed, it produces the following results:

第一本书标题 : C++ 教程
第一本书作者 : Example
第一本书类目 : 编程语言
第一本书 ID : 12345
第二本书标题 : CSS 教程
第二本书作者 : Example
第二本书类目 : 前端技术
第二本书 ID : 12346

Structures as function parameters

You can pass a structure as a function parameter, in a way similar to variables or pointers of other types. You can use the method in the above example to access structure variables:

Example

#include <iostream> #include <cstring> using namespace std; void printBook( struct Books book ); // Declare a struct type Books struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main( ) { Books Book1; // Define a variable Book1 of the struct type Books Books Book2; // Define a variable Book2 of the struct type Books // Book1 details strcpy( Book1.title, "C++ Tutorial"); strcpy( Book1.author, "Example"); strcpy( Book1.subject, "Programming language"); Book1.book_id = 12345; // Book2 details strcpy( Book2.title, "CSS Tutorial"); strcpy( Book2.author, "Example"); strcpy( Book2.subject, "Front-end technology"); Book2.book_id = 12346; // Output Book1 information printBook( Book1 ); // Output Book2 information printBook( Book2 ); return 0; } void printBook( struct Books book ) { cout << "Book title:" << book.title <<endl; cout << "Book author:" << book.author <<endl; cout << "Book category:" << book.subject <<endl; cout << "Book ID:" << book.book_id <<endl; }

When the above code is compiled and executed, it produces the following results:

书标题 : C++ 教程
书作者 : Example
书类目 : 编程语言
书 ID : 12345
书标题 : CSS 教程
书作者 : Example
书类目 : 前端技术
书 ID : 12346

Detailed introduction to the various parts of a structure

  • struct keyword:is used to define a structure; it tells the compiler that what follows is a custom type.

  • Member variables:Member variables are data items defined in a structure; they can be of any basic type or other custom types. In a struct, these members are public by default and can be accessed directly.

  • Member functions:Structures can also contain member functions, making them functionally similar to classes. Member functions can operate on the structure's member variables, providing encapsulation and manipulation of data.

  • Access permissions:Similar to class, you can use public, private, and protected in struct to define member access permissions. In struct, all members are public by default, while in class they are private by default.

Pointer to a structure

You can define pointers to structures in a manner similar to defining pointers to variables of other types, as shown below:

struct Books *struct_pointer;

The above code defines a pointer struct_pointer to the Books structure.

Now, you can store the address of a structure variable in the pointer variable defined above. To find the address of a structure variable, place the&operator before the structure name, as shown below:

struct_pointer = &Book1;

The above code assigns the address of the Book1 structure variable to struct_pointer.

To access the members of a structure using a pointer to that structure, you must use->operator, as shown below:

struct_pointer->title;

The above code accesses the title member of the Book1 structure through struct_pointer.

Let's use a structure pointer to rewrite the above example, which will help you understand the concept of structure pointers:

Example

#include <iostream> #include <string> using namespace std; // Declare a struct type Books struct Books { string title; string author; string subject; int book_id; // constructor Books(string t, string a, string s, int id) : title(t), author(a), subject(s), book_id(id) {} }; // Function to print book information, takes a pointer to the Books struct void printBookInfo(const Books* book) { cout << "Book title:" << book->title << endl; cout << "Book author:" << book->author << endl; cout << "Book category:" << book->subject << endl; cout << "Book ID:" << book->book_id << endl; } int main() { // Create two book objects Books Book1("C++ Tutorial", "Example", "Programming language", 12345); Books Book2("CSS Tutorial", "Example", "Front-end technology", 12346); // Use pointers to point to the objects of these two books Books* ptrBook1 = &Book1; Books* ptrBook2 = &Book2; // Output book info, pass pointers printBookInfo(ptrBook1); printBookInfo(ptrBook2); return 0; }

Description:

  • Struct definition:BooksThe definition of the structure is the same as before, containingtitle、author、subjectandbook_idfour member variables, and there is a constructor for initializing these members.

  • printBookInfoFunction: Now this function accepts a pointer toBooksPointer to a structureconst Books* book. Inside the function, we use->operator to access the member variable pointed to by the structure pointer.

  • mainFunction:

    • Created twoBooksobjects of typeBook1andBook2。

    • Usage&operator to get the addresses of the two objects and assign them to the pointersptrBook1andptrBook2。

    • CallprintBookInfoWhen passing the function, what is passed is a pointer toBooksPointer to an object.

When the above code is compiled and executed, it produces the following results:

书籍标题: C++ 教程
书籍作者: Example
书籍类目: 编程语言
书籍 ID: 12345
书籍标题: CSS 教程
书籍作者: Example
书籍类目: 前端技术
书籍 ID: 12346

typedef keyword

Below is a simpler way to define a structure: you can give an alias to the created type. For example:

typedef struct Books
{
   char  title[50];
   char  author[50];
   char  subject[100];
   int   book_id;
}Books;

Now, you can directly useBooksto defineBooksvariables of this type, without needing the struct keyword. Here is an example:

Books Book1, Book2;

You can usetypedefkeyword to define non-structure types, as shown below:

typedef long int *pint32;
 
pint32 x, y, z;

x, y, and z are all pointers to long int.


Differences between structures and classes

In C++, struct and class are essentially very similar; the only difference is the default access permission:

  • structDefault member access and inheritance arepublic。
  • classDefault member access and inheritance areprivate。

You canstructtreated as a simplified form ofclass, suitable for simple data encapsulation without too many complex features.

Combining structures with functions

You can initialize a structure via a constructor, and you can also pass a structure by reference to avoid unnecessary copies.

Example

struct Books {
    string title;
    string author;
    string subject;
    int book_id;

    // constructor
    Books(string t, string a, string s, int id)
        : title(t), author(a), subject(s), book_id(id) {}

    void printInfo() const {
        cout << Book Title: << title << endl;
        cout << Book Author: << author << endl;
        cout << Book Category: << subject << endl;
        cout << Book ID: << book_id << endl;
    }
};

void printBookByRef(const Books& book) {
    book.printInfo();
}
other extensions