C++ Struct结构体用法浅析

前边我们所定义的类,均是使用struct关键字来定义,但是C++中真正用于定义类的关键字为class,因为要C++兼容C,所以保留struct关键字,struct与class的用法完全相同

一.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;

到此这篇关于C++ Struct结构体用法浅析的文章就介绍到这了,更多相关C++ Struct结构体内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是C++ Struct结构体用法浅析的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言