C和C++中Struct结构体的区别

Struct(结构体) C和C++区别

  1. c语言中,结构体是不允许有函数的,但是在c++中可以;

    如下,c++中结构体:

    c 复制代码
    struct PetInfo
    {
        string name; // Pet name
        string type; // Pet type
        int age; // Pet age
        CostInfo cost;
        PetInfo() // Default constructor
        {
            name = "unknown";
            type = "unknown";
            age = 0;
            cost.food = cost.medical = cost.license = cost.misc = 0.00;
        }
    };
  2. c语言中结构体不能继承,但是c++可以继承;

    如下,结构体B继承结构体A:

    c 复制代码
    struct B : public A//结构B继承A
    {
        int c;
        B(int a,int b,int c);
        virtual ~B();
    
        virtual void Display(void);
        friend istream& operator >>(istream& in,struct B &b);
        friend ostream& operator <<(ostream& out,struct B &b);
    };
  3. c语言中结构体的使用必须要用别名或者使用struct;

    如下:

    c 复制代码
    struct student
    {
    	int age;
    	int num;
    	int sex;
    };
    
    struct sutdent stu;
    
    或者
    
    typedef struct student
    {
    	int age;
    	int num;
    	int sex;
    } stu;
  4. c语言中默认是共有的,不可以修改权限,在c++中权限是可以修改的。

  5. c语言中不可以初始化数据成员,c++中可以初始化

    如下:

    c 复制代码
    struct Employee
    {
       string name;    // 员工姓名
       int vacationDays,    // 允许的年假
       daysUsed;    //已使用的年假天数
       Employee (string n ="",int d = 0)    // 构造函数
       {
           name = n;
           vacationDays = 10;
           daysUsed = d;
       }
    };
  6. c语言中空结构体大小为0,c++中空结构体为1。

相关推荐
Dream it possible!17 分钟前
LeetCode 热题 100_寻找重复数(100_287_中等_C++)(技巧)(暴力解法;哈希集合;二分查找)
c++·leetcode·哈希算法
丶Darling.1 小时前
Day119 | 灵神 | 二叉树 | 二叉树的最近共公共祖先
数据结构·c++·算法·二叉树
思茂信息2 小时前
CST软件对OPERA&CST软件联合仿真汽车无线充电站对人体的影响
c语言·开发语言·人工智能·matlab·汽车·软件构建
川川菜鸟2 小时前
2025长三角数学建模C题完整思路
c语言·开发语言·数学建模
醍醐三叶2 小时前
C++文件操作--2 二进制文件操作
开发语言·c++
li星野2 小时前
C++:C++内存管理
开发语言·c++
溟洵2 小时前
【C++ Qt】布局管理器
开发语言·c++·qt
我家大宝最可爱3 小时前
c++动态链接库
开发语言·c++
云海听雷3 小时前
C语言中字符串函数的详细讲解
c语言·笔记·学习
乌萨奇也要立志学C++3 小时前
【C++详解】string各种接口如何使用保姆级攻略
c++