C++ Struct结构体用法浅析

一.C语言 Strcut基本用法

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

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

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

例如:

struct student
{
 char name[20];
 int id;
 float chinese;
 float english;
 float math;
};

结构体的调用:

struct 结构体 结构体名;

结构体名.变量名 =

例如:

struct student s1;
s1.id = 20191028456;
s1.math = 95;

二.C++Strcut基本用法

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

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

struct student
{
 char name[20];
 int id;
 float chinese;
 float english;
 float math;
};
student s2;
s2.id = 20191031256;
s2.math = 60;

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

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

struct student
{
 char name[20];
 int id;
 float chinese;
 float english;
 float math;
}st3,st4;

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

struct
{
 char name[20];
 int id;
 float chinese;
 float english;
 float math;
}st5;

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

三.typedef 定义结构体

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

例如:

typedef struct student
{
 char name[20];
 int id;
 float chinese;
 float english;
 float math;
}student_inf;

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

student_inf s1;
 s1.chinese = 95;
 s1.id = 1;
作者:赵大宝字原文地址:https://blog.csdn.net/qq_35902025/article/details/129846178

%s 个评论

要回复文章请先登录注册