c++语言入门教程–-17结构体

218 阅读1分钟

c++语言入门教程–-17结构体

用 struct 声明
方法1
struct Books
{
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

方法2
struct
{
int a;
char b;
double c;
} S;

S s;

//我们可以将S看做一个类型,像一个int一样所以S s;这就是一个声明

s. a
s.b
s.c
这些就可以当做正常的变量使用。

我们还可以声明结构体数组
S s[5];

s[0]. a
s[0].b
s[0].c

例子:

#include <iostream>
#include <string.h>
using namespace std;
 
struct Books
{
   char  title[50];
   char  author[50];
   int   book_id;
} book;

int main ()
{
   gets(book.title); 
   gets(book.author); 
   scanf("%d",&book.book_id);
   
   cout<<"书名:"<<book.title<<endl;
   cout<<"作者:"<<book.author<<endl;
  cout<<"图书编号:"<<book.book_id<<endl;
    
   return 0;
}

运行结果:
在这里插入图片描述
在上面的例子,我们可以看出我们把书比作一个整体,然后书里面有书名,作者,图书编号等属性。
以后类似这样的事物,我们都可以用结构体来表示。