1.定义
结构体是自定义类型的一种,是cpp提供扩展自定义类型的一种方式。
2.声明
结构体的声明方式有2种:
第一种是:
struct user_type {
type name;
type name1;
type name2;
}variables;//variables可有可无
第二种是:
type struct{
type name;
type name1;
type name2;
} user_type;
3.实例
#include <iostream>
#include <ctime>
#include <cstring>
using namespace std;
typedef struct{
int book_id;
char book_title[10];
char book_description[100];
time_t book_pubtime;
} Book;
//struct Book{
// int book_id;
// char book_title[10];
// char book_description[100];
// time_t book_pubtime;
//}book;
int main(int argc, char *argv[])
{
book.book_id=12;
strcpy(book.book_title,"book_title");
strcpy(book.book_description,"book_description");
book.book_pubtime=time(0);
cout<<"book_id:"<<book.book_id <<endl;
cout<<"book_title:"<<book.book_title <<endl;
cout<<"book_description:"<<book.book_description <<endl;
cout<<"book_pubtime:"<<ctime(&book.book_pubtime)<<endl;
return 0;
}
4.补充
结构体变量的声明:struct user_type name;或者user_type name;
结构体指针变量的声明:struct user_type* name;