当前位置:   article > 正文

【C++】 Struct用法详解_c++ struct

c++ struct

 一.C Strcut基本用法

C语言声明结构体的几种方式

struct 结构体名
{
    数据类型  变量名1;
};

其中的数据类型既可以是约定好的int、char、float等数据类型,也可以是结构体类型(在定义此处结构体之前已经定义完成)。
例如:

  1. struct student
  2. {
  3.     char name[20];
  4.     int id;
  5.     float chinese;
  6.     float english;
  7.     float math;
  8. };

结构体的调用:

struct 结构体 结构体名;
结构体名.变量名 = 

例如:

  1. struct student s1;
  2. s1.id = 20191028456;
  3. s1.math = 95;

二.C++ Strcut基本用法

C++语言将struct当成类来处理的,所以C++的struct可以包含C++类的所有东西,例如构造函数,析构函数,友元等。

与C中struct比较明显的一个区别是,C++允许在声明结构体变量时省略关键字struct

  1. struct student
  2. {
  3.     char name[20];
  4.     int id;
  5.     float chinese;
  6.     float english;
  7.     float math;
  8. };
  1. student s2;
  2. s2.id = 20191031256;
  3. s2.math = 60;

C++也支持其他集中结构体定义方式

1.结构体定义时同时声明结构体变量

  1. struct student
  2. {
  3.     char name[20];
  4.     int id;
  5.     float chinese;
  6.     float english;
  7.     float math;
  8. }st3,st4;

2.省略结构体名称同时声明结构体变量

  1. struct
  2. {
  3.     char name[20];
  4.     int id;
  5.     float chinese;
  6.     float english;
  7.     float math;
  8. }st5;

这种方式同样可以使用st5.id去访问成员,但是这种类型没有名称,不能使用名称去创建这种类型的结构体变量,不建议使用。

三.typedef 定义结构体

使用typedef定义可以不写struct,定义变量的时候方便许多。
例如:

  1. typedef struct student
  2. {
  3. char name[20];
  4. int id;
  5. float chinese;
  6. float english;
  7. float math;
  8. }student_inf;

在使用时,可直接用student_inf来定义变量,如:

  1. student_inf s1;
  2. s1.chinese = 95;
  3. s1.id = 1;
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/714782
推荐阅读
相关标签
  

闽ICP备14008679号