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。

相关推荐
博客18002 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴2 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨2 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4566 天前
C++进阶(1)——前景提要
c++
夜悊7 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴7 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0017 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
LDR0067 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
Luminous.7 天前
C语言--day30
c语言·开发语言
玖玥拾7 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器