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。

相关推荐
老四啊laosi1 天前
[C++进阶] 24. 哈希表封装unordered_map && unordered_set
c++·哈希表·封装·unordered_map·unordered_set
妙为1 天前
银河麒麟V4下编译Qt5.12.12源码
c++·qt·国产化·osg3.6.5·osgearth3.2·银河麒麟v4
weixin_446023561 天前
C语言:面向过程、应用底层开发、跨平台的通用程序设计语言
c语言·跨平台·数据类型·底层开发·面向过程
无敌昊哥战神1 天前
深入理解 C 语言:巧妙利用“0地址”手写 offsetof 宏与内存对齐机制
c语言·数据结构·算法
史迪仔01121 天前
[QML] QML IMage图像处理
开发语言·前端·javascript·c++·qt
cmpxr_1 天前
【C】数组名、函数名的特殊
c语言·算法
会编程的土豆1 天前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
低频电磁之道1 天前
解决 Windows C++ DLL 导出类不可见的编译错误
c++·windows
itman3011 天前
C语言怎么学?从写程序到玩指针的实操攻略
c语言·指针·结构体·编程学习·资源推荐
君义_noip1 天前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s