C/C++ 结构体Struct区别

struct关键字是一种程序定义的数据类型,用户可以自定义其中的数据项

C语言的Struct

C中的struct用来存放一组不同的数据,其中的数据项只能为变量,而不能为函数

定义格式

struct type_name {
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
...
}

定义变量

C语言中初始化结构体变量有4种方式,例如定义一个结构体Employee

struct Employee
{
    int id {};
    int age {};
    double wage {};
};

并对其进行初始化

// 1
struct Employee joe, mary; //定义两个变量
joe.id = 123;
joe.age = 32
joe.wage = 20000;

//2 
struct Employee joe(123, 32, 20000), mary(234, 29, 8000); //定义变量并初始化

//3 
struct Employee
{
    int id {};
    int age {};
    double wage {};
}mary, joe = {123, 32, 20000} //将变量放在结构体定义最后,大括号后分号前

//4
struct {
    int id {};
    int age {};
    double wage {};
}joe = {123, 32, 20000} // 若后续不再定义此结构体变量,可忽略结构提名称(Employee)

C++中的struct

C++中的struct继承至c中的struct,因此有相似也有不同
由于C++既可以面向过程也可以面向对象编程,因此c++中的structclass类似,可以包含成员变量,也可以包含成员函数

定义结构体

struct Employee
{
    int id {};
    int age {};
    double wage {};
    Employee(){ //构造函数, 名称必须与结构体相同
    id = 123
    age = 32;
    wage = 20000;
    };
};

定义变量

//C++ 变量初始化可以省略`struct`关键字
struct Employee joe;
Employee joe;

c++中的structclass基本通用,但又有不同

  1. class默认成员为private属性,而struct默认成员为public属性
  2. class继承默认为private继承, 而struct继承默认为public继承
  3. class可以使用模板,而struct不能

Ref

  1. https://www.learncpp.com/cpp-tutorial/introduction-to-structs-members-and-member-selection/
  2. https://www.cnblogs.com/banluxinshou/p/11823158.html
posted @   liuliu55  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
点击右上角即可分享
微信分享提示