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:
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:
Advantages of structures:
- Simple data encapsulation: suitable for encapsulating simple data of multiple types, usually used for data storage.
- Lightweight: compared to
class, 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
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
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
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 two
Booksobjects of typeBook1andBook2。Usage
&operator to get the addresses of the two objects and assign them to the pointersptrBook1andptrBook2。Call
printBookInfoWhen 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
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();
}