C++数据结构允许存储不同类型的数据项(数组存储的是相同类型数据)。
定义结构使用struct语句,其定义了包含多个成员的新的数据类型,语法格式如下:
struct type_name{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
...
} object_names;
type_name:结构体类型的名称
member_type1 member_name1:标准的变量定义,比如 int i、float f,或其他有效的变量定义。
在结构定义的末尾,最后一个分号之前,可以指定一个或多个结构变量,可选。
实例:
#include <iostream>
#include <cstring>
using namespace std;
// 声明一个结构体类型 Books
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main()
{
Books Book1; //定义结构体类型Books的变量Book1
Books Book2; //Books Book2
// Specification of Book1
strcpy_s(Book1.title, "C++ Tutorial"); (备注:在vs2019版如果使用 strcpy,会导致程序无法运行)
strcpy_s(Book1.author, "Runoob");
strcpy_s(Book1.subject, "Program language");
Book1.book_id = 12346;
// Specification of Book2
strcpy_s(Book2.title, "CSS Tutorial");
strcpy_s(Book2.author, "Runoob");
strcpy_s(Book2.subject, "Front Technology");
Book2.book_id = 12345;
// output information of book1
cout << "Title of first book: " << Book1.title << endl;
cout << "Author of first book: " << Book1.author << endl;
cout << "Subject of first book: " << Book1.subject;//<< endl;
cout << "book_id of first book: " << Book1.book_id << endl;
return 0;
}