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。

相关推荐
小张成长计划..1 小时前
【C++】2:cin和cout的介绍和使用,函数的缺省参数
c++
再卷也是菜1 小时前
C++篇(17)哈希拓展学习
c++·哈希
“愿你如星辰如月”1 小时前
Linux:进程间通信
linux·运维·服务器·c++·操作系统
灵晔君2 小时前
C++标准模板库(STL)——list的模拟实现
c++·list
Justinyh3 小时前
1、CUDA 编程基础
c++·人工智能
white-persist4 小时前
差异功能定位解析:C语言与C++(区别在哪里?)
java·c语言·开发语言·网络·c++·安全·信息可视化
ShineWinsu4 小时前
对于数据结构:链式二叉树的超详细保姆级解析—中
数据结构·c++·算法·面试·二叉树·校招·递归
liu****5 小时前
20.传输层协议TCP
服务器·网络·数据结构·c++·网络协议·tcp/ip·udp
沐怡旸5 小时前
【穿越Effective C++】条款20:宁以pass-by-reference-to-const替换pass-by-value——参数传递的效率与语义
c++·面试
八个程序员5 小时前
c++音乐——《两只老虎》
c++·游戏